2017-07-03 67 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

相关问题