2017-11-25 14 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

関連する問題