2017-11-25 7 views
0

요소를 성공적으로 추가하는 서비스를 사용하여 배열에 요소를 추가하고 있습니다. 데이터가 console.log로 채워진 것을 볼 수 있습니다.배열 요소에 액세스 할 수 없습니다.

그러나 요소에 액세스 할 수는 없습니다.

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

내가 '정의되지 않은'의 출력을 얻을 : 나는 같은 것을 사용하지만

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

. 나는 내가 지금 어떻게 접근하고 있는지에 대해 정말로 두꺼운 지 잘 모르겠다. ...

아이디어가 있으십니까?

+0

당신은 당신이 (JSON.stringify (this.openSet))을 console.log를 할 때 표시 게시 할 수 있습니다; – 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