2016-12-30 67 views
1

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

你可以分享样本'数据'?此外,我猜问题是'this'而不是'data' – Rajesh

+0

是的,问题在于'this',这就是为什么我做了'this.code ='test'',其失败了 – Kiwi

+2

在我的理解中,你将不得不像''.map(x => new Warehouse(x))' – Rajesh

回答

0

你似乎是通过构造成阵图功能,这可能不是你想要

def.resolve(r.data.map(Warehouse)); 

也许应该是什么

def.resolve(new Warehouse(r.data)); 

函数r.data.map(FN)接受一个函数并返回一个数组,该数组由eac h元素E,并用E作为参数调用该函数,如FN(E)中所示。见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

+0

我做了一个假设,您根本不需要map函数,因为您的构造函数基本上期望获得数据obj,并且已经在其中执行深层副本。 – softwarenewbie7331

+0

这不是我想要的,因为我希望每个'r.data'都是Warehouse类型的;) – Kiwi

+0

在这种情况下,Rajesh的评论可能是你想要的 – softwarenewbie7331