[英]Why is Angular component property undefined after http.get
為什么在http.get之后的構造函數中未定義“this.Trails”?
http.get是成功的,但“ this.Trails ”一直未定義。 不過,在我的頁面中,我可以輸出項目。 我不明白這一點。
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
}
Http.get() 是一個異步調用,它將在下一個滴答聲中得到處理(在它被解析或拒絕之后)
if (this.Trails != undefined) {
console.log("has items");
}
以上代碼在訂閱前執行
this.Trails = result.json();
因此不設防
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.