Having an issue while trying to iterate over an array in Angular. Despite initializing and filling the array, the loop doesn't seem to work as expected.
The array is populated in the following manner. It is logged in the console to confirm that it has been successfully filled.
export class CarDetailsComponent implements OnInit, AfterViewInit {
cars: Array<Car>;
constructor(private carService: CarService) {}
ngOnInit() {
this.cars = this.carService.getCars();
console.log(this.cars);
}
}
The array is meant to be processed in ngAfterViewInit()
. After confirming the array is not empty, the loop still fails to execute the console.log statement. Why might that be?
ngAfterViewInit() {
console.log(this.cars);
for (let i in this.cars) {
console.log(i);
}
}
Attempts to use for..of
, this.cars.slice()
and other methods yield the same unexpected result...
EDIT (addressing some suggestions in comments)
After implementing both log suggestions, it became apparent that the array is empty. The discrepancy between console.log(this.cars)
showing a valid array and this.cars.length
and JSON.stringify(this.cars)
returning empty values is puzzling.
As a beginner, I am uncertain about the cause of this behavior. It may be related to the insights provided by @Ayman and @Codeepic.
https://i.sstatic.net/Uiaub.png
EDIT 2
In response to @Minko's inquiry, I believe the function is synchronous. Simplified, it looks like:
getCars(): Array<Car> {
var cars: Car[] = [];
this.http.get('//localhost:8080/cars).subscribe(data => {
for (let entry of <Array<any>>data) {
cars.push(entry);
}
});
return cars;
}