2016-11-28 13 views
2

我得到這個代碼AppComponent:無法讀取屬性 '名' 空的Angular2 JSON

getPlanetsToView(page){ 
    let pageToView = page*10 + 10; 

    for(var i=0; i<pageToView; i++){ 
    this.planetsToView.push(this.planets.planets[i]); 
    } 

} 

ngOnInit() { 
    this.http.get('app/planets.json').subscribe(res => { 
    this.planets = res.json(); 
    console.log(this.planets); 
    this.getPlanetsToView(0); 
    }); 

而且我有這個模板:

{{planetsToView[0].name | json}} 

我有問題: Photo

當我嘗試{{planetsToView [0] | json}}它可以工作,但也包含其他屬性。

回答

3

可能是這個問題:

在你的組件被初始化您的JSON尚未裝入this.planets因爲http.get調用是異步的時間。你可以在你的模板試試這個:(注意其中加入?)

{{planetsToView[0]?.name | json}} 

被稱爲elivs操作符,用於在視圖模板中安全防範未定義的引用。在這裏閱讀更多:

+0

當我做到了,我得到了錯誤: main.browser.ts:10錯誤:模板解析錯誤:(...) –

+1

我不知道是錯誤,但是當我把它抄了,開始工作。謝謝! –