Reputation: 326
Why is "this.Trails" undefined in the constructor after http.get?
The http.get is succesfull, but "this.Trails" is undefined all the way. Still, in my page I am able to output the items. I don't understant this.
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'salvamont',
templateUrl: './salvamont.component.html'
})
export class SalvamontComponent {
public Trails: HikingTrail[];
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + 'api/SampleData/HikingTrails')
.subscribe(result => {
this.Trails = result.json();
},
error => console.error(error));
if (this.Trails != undefined) {
console.log("has items");
}
}
}
class HikingTrail {
//some members
}
Upvotes: 2
Views: 282
Reputation: 524
Http.get() is an async call which will get processed on next tick (after it is resolved or rejected)
if (this.Trails != undefined) {
console.log("has items");
}
The above code is executed before the subscription
this.Trails = result.json();
Thus undefiend
Upvotes: 3