2016-12-30 110 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