繁体   English   中英

Array.map()到Class给出了undefined

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

我正在尝试使用数组的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
  }
]

您似乎将构造函数传递给数组映射函数,这可能不是您想要的

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

暂无
暂无

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

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