0

I'm adding elements to an array using a service, which successfully adds the elements. I can see the data populated with a console.log

I can't however access the element.

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

However, when I use something like:

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

I get output of 'undefined'. I'm not sure if I'm being really thick right now in how I'm accessing it or not...

Any ideas?

6
  • can you post what you see when you do console.log(JSON.stringify(this.openSet)); Commented Nov 25, 2017 at 16:31
  • please add the javascript tag to the question Commented Nov 25, 2017 at 16:32
  • 2
    Possible duplicate of How to return the response from an asynchronous call? Commented Nov 25, 2017 at 16:33
  • @baao how will this question be a duplicate of the one you mentioned. Can you elaborate? Commented Nov 25, 2017 at 16:36
  • Explained in the community wiki answer @Aravind Commented Nov 25, 2017 at 16:39

1 Answer 1

1

subscribe works asynchron, so console.log() will log before the forEach loop runs. It's the same async behaviour as in this little piece of code

let foo = [];

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

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

Please see the duplicate post for options on how to work with asynchronity.

How to return the response from an asynchronous call?

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I see what you mean. printing out the array using JSON.stringify returned empty, so confirms your answer. Thank you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.