I'm trying to iterate over an array, but Angular refuses to step in into it...
The array is being filled as follows. As you can see, I'm printing it into the console, and I can see that the array was initialized and 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 will be consumed into a ngAfterViewInit(). For debug purposes, the first thing that I did was to check if the array is ok. And it is. But, the console.log inside the loop is never called. Why?
ngAfterViewInit() {
console.log(this.cars);
for (let i in this.cars) {
console.log(i);
}
}
I also tried to for..of, this.cars.slice() and everything seems to be ok...
EDIT (addressing some suggestions in comments)
I added both log suggestions and they show that the array is empty. I've attached a printscreen that shows that console.log(this.cars) shows a valid array, but this.cars.length and JSON.stringify(this.cars) doesn't.
Since I'm noob, I don't know why this behavior occurs. Probably it related with what @Ayman and @Codeepic pointed out.
EDIT 2
Regarding @Minko question, I think that it is synchronous. 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;
}

getCarssynchronous?this.cars.forEach(function(car) { console.log(car); });should work if the cars array has elementsconsole.log('number of cars: ' + this.cars.length);getCars()looks very asynchronous due to the GET request and the following callback which fills the array.