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?