-1

I am trying to initialize an array from a Json file using HttpClient using the folowing code (there is a simple HttpClient service in dr):

getData() {
  this.dr.getData().subscribe(data => {
    for (const d of (data as any)) {
      this.ants.push({
        x: d.x,
        y: d.y
      });
    }
    console.log("1st log : " + this.ants);
  });
  console.log("2nd log : " +this.ants);
}

The logs give the following result :

2nd log : 
1st log : [object Object],[object Object]

The array is properly initialized int he first log, but it is executed after the second log, in which the array is empty. I use getData() in ngOnInit(), and I want to use the result (the initialized ant array) in the showData() function:

ngOnInit() {
  this.getData();
  this.ctx = this.canvas.nativeElement.getContext('2d');
  this.showData();
}

But like in the 2nd log, the array is empty when executing showData(). Does anyone have any idea why this is happening, and how to fix it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

subscribe is asynchronous, it means it wasn't executed at moment when you call console.log("2nd log : " +this.ants); (its outside of subscription callback).

If your code depends on the result of this.dr.getData().subscribe then move it inside of the callback.

satanTime
  • 12,631
  • 1
  • 25
  • 73