简体   繁体   English

Array.map()到Class给出了undefined

[英]Array.map() to Class gives undefined on this

I'm trying to use the map function of the array to map my data to a specific class. 我正在尝试使用数组的map函数将我的数据映射到特定的类。 The project is in Angular. 该项目位于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: 然后在我的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;
        }
    }
}

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: 所以只是值的副本,但奇怪的是,它已经在this.code = 'test'上出现错误,然后我得到错误:

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). 函数r.data.map(FN)接受一个函数并返回一个数组,该数组来自r.data的每个元素E,并以E作为参数调用该函数,如FN(E)。 see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map 请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM