在我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的解決方案最容易理解/遵循並且沒有錯誤。
這是一個異步調用@SeanUrgel你可能需要以異步方式將所有內容放入第一個可觀察對象中,或者使用開關或平面映射 –