I am currently facing an issue where I am trying to populate an array from a JSON file using HttpClient. Below is the code snippet that I am using, utilizing 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);
}
Upon checking the logs, I see the following result :
2nd log :
1st log : [object Object],[object Object]
The challenge lies in the fact that the array initialization occurs after the second log, leading to an empty array at that point. I have the getData() function called within ngOnInit(), and I intend to utilize the initialized ant array in the showData() function:
ngOnInit() {
this.getData();
this.ctx = this.canvas.nativeElement.getContext('2d');
this.showData();
}
However, similar to the observations made in the 2nd log, the array appears to be empty when executing showData(). Any insights on what might be causing this behavior and how to address it would be greatly appreciated.