2017-11-25 137 views
0

我使用服务将数组元素添加到数组中,该服务成功添加了元素。我可以看到使用console.log登录的数据无法访问数组的元素

但我无法访问该元素。

this.routingService.getNode(startNode).subscribe(node => { 
     node.forEach(node => { 
     this.openSet.push(new MapNode(node.id, node.lon, node.lat, this.routingService.getNodeNeighbours(node.id))); 
     }); 
    }); 

    console.log(this.openSet); // this prints out the below screenshot 

enter image description here

然而,当我使用类似:

console.log(this.openSet[0]); 

我得到的 '未定义' 输出。我不确定我现在是否真的很厚我现在在访问它或不...

任何想法?

+0

你可以发布你所看到的,当你做的console.log(JSON.stringify(this.openSet)); – Sajeetharan

+0

请将javascript标签添加到问题 – baao

+2

[如何从异步调用返回响应?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-一个异步调用) – baao

回答

1

subscribe工作异步,因此console.log()将在forEach循环运行之前记录。这是相同的异步行为,在这一小段代码

let foo = []; 
 

 
setTimeout(() => { 
 
    foo.push(1); 
 
    foo.push(2); 
 
}, 500); 
 

 
console.log(foo); // logs []

请参阅重复的职位如何与asynchronity工作选择。

How to return the response from an asynchronous call?

+0

啊,我明白你的意思了。使用JSON.stringify打印数组返回空,所以确认你的答案。谢谢! :) – Travisty