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?

Travisty
  • 195
  • 2
  • 11

1 Answers1

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?

baao
  • 71,625
  • 17
  • 143
  • 203
  • Ah, I see what you mean. printing out the array using JSON.stringify returned empty, so confirms your answer. Thank you! :) – Travisty Nov 25 '17 at 16:50