2017-07-03 102 views
0

我試圖遍歷由對象組成的對象,其中每個對象的一個​​屬性用於進行服務調用。Typescript - 從ForEach()中重複調用函數導致未定義

這很好,當我嘗試這樣做一次,我可以控制檯註銷從成功的服務調用返回的數據,但是當我嘗試使用forEach()爲父對象中的每個對象重複此過程我收到錯誤「Can not read property'host'of undefined」。

有人可以解釋我失蹤了嗎?

這是一個什麼樣的例子我的代碼看起來像現在:

getItemParametersCallback(data){ 
    ... 
    // Parent Object made of Objects 
    // data is returned by a service call 
    this.parentObject = data.json(); 

    // Iterate through the objects of the parentObject 
    const parentObjectItems = Object.keys(this.parentObject); 

    parentObjectItems.forEach(key => { 
     // I can add an if to limit this to being called once, 
     // like if(key === 'apple')... and it works fine 
     this.ItemService.getItem(this.getItemCallback.bind(this), 
      this.parentObject[key]); 
    }); 
} 

// Console log out the data returned 
getItemCallback(data){ 
    console.log(data); 
} 
+1

嘗試做的console.log(this.parentObject) - 也許它缺少一些特性。 – libertyernie

+0

不幸遺失財產。我可以用if語句將foreach限制在2個屬性中,我知道每個屬性都會單獨返回,而不是當我嘗試執行這兩個屬性時。不過謝謝。 – gv0000

+1

getItem或getItemCallback方法是否會以某種方式改變狀態? –

回答

1

從代碼:

this.parentObject = data.json(); 

// Iterate through the objects of the parentObject 
const parentObjectItems = Object.keys(this.parentObject); 

data.json/.json方法返回一個承諾。所以Object.keys(this.parentObject)是錯誤的。

解決方案

使用.thenasync/await解開延續。

更多

+0

那麼這樣的事情呢? 。 \t \t'常量entityValues = value.json(),然後(數據=>({ \t \t \t \t \t \t \t \t \t \t \t \t \t數據:數據, \t \t \t \t \t \t \t \t \t \t \t \t \t狀態:數據。狀態 \t \t \t \t \t \t \t \t \t \t \t \t \t}) \t \t \t \t \t \t \t \t \t \t \t \t \t \t)。然後(RES => { \t \t \t \t \t \t \t \t \t \t \t \t \t \t的console.log(res.status,res.data.title) \t \t \t \t \t \t \t \t \t \t \t \t \t \t});' – gv0000

+0

@ gv0000的確 – basarat

相關問題