Marcel Jacques Machado Marcel Jacques Machado - 26 days ago 8
TypeScript Question

How to get the elements of an array returned by a service in Angular 2?

I'm learning Angular 2 + PrimeNG and I'm studying this quick start project: https://github.com/primefaces/primeng-quickstart

It's a CRUD and works very well. All the data is being shown in a table in my browser. Great!

Now I'm trying to change the code a little bit. All works fine, except my stupid code.

export class AppComponent {

displayDialog: boolean;

car: Car = new PrimeCar();

selectedCar: Car;

newCar: boolean;

cars: Car[];

constructor(private carService: CarService) { }

ngOnInit() {
this.carService.getCarsMedium().then(cars => this.cars = cars);

//THIS IS MY CODE:
console.log(this.cars);
for (let entry of this.cars) {
console.log(entry);
}
}


The first
console.log
gives me an
undefined
message. Then the
for
breaks the application.

So I'm basically trying to show in the console the same data that is shown in the browser. Someone could help me with that?

Thanks! =)

Answer

You need to move the code that depends on the observable result inside then(...), otherwise the code will be executed before the value is available

ngOnInit() {
    this.carService.getCarsMedium().then(cars => {
        this.cars = cars
        //THIS IS MY CODE:
        console.log(this.cars);            
        for (let entry of this.cars) {
            console.log(entry);
        }
    });

}