2017-09-13 54 views
0

在我ItemDetailComponentAngular 2或4,生命週期鉤子是對的?

我有這樣的下面的代碼:

item: Item; 
param: string; 

ngOnInit() { 
    this.activatedRoute.params.subscribe((params: Params) => { 
     this.param = params.id; 
    }); 
    this.itemService.getItem(this.param).subscribe(
         item => this.item = item, 
         err => console.error(err) 
        ) 
    } 

和我ItemService我:

getItem(id: string) { 
return this.http.get(`http://localhost:3000/items/${id}`) 
       .map((response: Response) => { 
        const temp = response.json().obj; 
        const item = new Item(temp.model, temp.description, temp.price, temp.type, temp.imagePath, temp.longDescription, temp._id); 
        return item; 
       }) 
       .catch((error: Response) => Observable.throw(error.json())); 

}

所以TLDR; 從數據庫取決於_id

這個工程項目檢索,但問題是HTML組件,加載之前,我可以檢索數據。所以,我得到這個錯誤的項目被檢索之前

ERROR TypeError: Cannot read property 'ImagePath' of undefined 

所以基本上呈現HTML - 因爲項目仍然是不確定的蒙上錯誤。但後來,當項目從數據庫中檢索時工作。

有沒有解決方案呢?我是否使用了錯誤的生命週期鉤子?即使它行得通 - 我覺得我可以做得更好。任何建議/解決方案?

編輯:謝謝你所有的答案,但我相信Suren Srapyan的解決方案最容易理解/遵循並且沒有錯誤。

+0

這是一個異步調用@SeanUrgel你可能需要以異步方式將所有內容放入第一個可觀察對象中,或者使用開關或平面映射 –

回答

0

對於每個生命週期鉤子,DOM準備好之前無法檢索項目。一種解決方案可以是使用ngIf指令來隱藏該部分標記,直到獲得所需的數據。

例如

<div ngIf="yourData"> 
    <p>{{ yourData.ImagePath }}</p> 
</div> 
1
ngOnInit() { 
    this.activatedRoute.params.subscribe((params: Params) => { 
     this.param = params.id; 
     this.itemService.getItem(this.param).subscribe(
      item => this.item = item, 
      err => console.error(err) 
     ) 
    }); 

} 

在HTML模板中使用{{item?.ImagePath}}安全操作?

0

一個其他的答案中使用預訂這是不是真的中訂閱RxJS最佳實踐。您最好使用flatMap運算符,該運算符將Observable發射的項目轉換爲Observable,然後將這些項目的排放變爲單個Observable。 http://reactivex.io/documentation/operators/flatmap.html

item: Observable<Item>; 
param: string; 

ngOnInit() { 
    this.item = this.activatedRoute.params.flatMap((params: Params) => { 
    this.param = params.id; 
    return this.itemService.getItem(this.param) 
    }); 
} 

在你的HTML,那麼你可以使用異步管道{{ item | async }}在你的HTML它將處理訂閱和可觀測項目的退訂。 https://angular.io/api/common/AsyncPipe

相關問題