我试图使用数组的map函数将我的数据映射到特定的类。该项目位于Angular。
所以我这样做:
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);
到目前为止非常基础。然后在我的Warehouse类中看起来像这样:
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
}
]
答案 0 :(得分:0)
您似乎将构造函数传递给数组映射函数,这可能不是您想要的
def.resolve(r.data.map(Warehouse));
应该是
def.resolve(new Warehouse(r.data));
函数r.data.map(FN)接受一个函数,并返回一个数组,该数组来自r.data的每个元素E,并以E作为参数调用函数,如FN(E)。见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map