我试图使用数组的映射函数来映射我的数据到一个特定的类。该项目在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