我試圖使用數組的映射函數來映射我的數據到一個特定的類。該項目在Angular中。Array.map()to Class給出undefined這
所以我做的:
me.$http({
url: me.appConfig.api + `customer/${customer.number}/stock/warehouses`,
method: 'get'
}).then((r: any) => {
def.resolve(r.data.map(Warehouse));
}).catch(def.reject);
非常基本至今。然後在我的倉庫類,它看起來是這樣的:
export class Warehouse {
code: string;
location: string;
weight: number;
count: number;
late: number;
stock?: Stock[];
constructor(data?: any) {
console.debug('test', data);
this.code = 'test';
if (data) {
this.code = data.code;
this.location = data.location;
this.weight = data.weight;
this.count = data.count;
this.late = data.late;
}
}
}
所以只是值的副本,但奇怪的是,它已經在this.code = 'test'
錯誤,然後我得到的錯誤:
TypeError: Cannot set property 'code' of undefined
at Warehouse (main.bundle.js:2218:19)
at Array.map (native)
任何線索爲什麼會發生這種情況?
的樣本數據:
[
{
"code": "SQD",
"location": "35,16161;6,31561",
"weight": 3200,
"count": 18,
"late": 18
},
{
"code": "GQZ",
"location": "35,16161;6,31561",
"weight": 321,
"count": 20,
"late": 18
}
]
你可以分享樣本'數據'?此外,我猜問題是'this'而不是'data' – Rajesh
是的,問題在於'this',這就是爲什麼我做了'this.code ='test'',其失敗了 – Kiwi
在我的理解中,你將不得不像''.map(x => new Warehouse(x))' – Rajesh