I'm trying to use the map function of the array to map my data to a specific class. The project is in Angular.
So I do:
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);
Pretty basic so far. Then in my Warehouse class it looks like this:
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;
}
}
}
So just a copy of the values, but the weird thing is, it already errors on the this.code = 'test'
then I get the error:
TypeError: Cannot set property 'code' of undefined
at Warehouse (main.bundle.js:2218:19)
at Array.map (native)
Any clue why this is happening?
Sample data:
[
{
"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
}
]
You appear to be passing a constructor into the array map function, which is probably not what you want
def.resolve(r.data.map(Warehouse));
should probably be
def.resolve(new Warehouse(r.data));
the function r.data.map(FN) takes a function and returns an array that results from taking each element E of r.data and calling the function with E as the parameter, as in FN(E). see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.