[英]Angular 2 ngOnInit Called Twice With Error
我在Angular 2中遇到了一個奇怪的錯誤。我有兩個類似的模板和類似服務的類似組件。 以下是它們如何工作的基礎知識:
零件:
theData: any;
constructor(private _theService: TheService) {}
ngOnInit() {
this._theService.getData()
.subscribe(data => {
this.theData = data;
});
}
服務:
private _url = "http://url.net/api/Data";
constructor(private _http: Http) {
}
getData() {
return this._http.get(this._url)
.map(res => res.json());
}
這將返回一個對象數組,如:
[
{name: "Name 1"},
{name: "Name 2"}
]
並且模板顯示如下:
<div *ngFor="let item of theData">{{ item.name }}</div>
然后,您可以單擊進入一個項目的項目,該項目遵循與上述相同的策略,但service / api僅返回單個對象,並且模板不使用* ngFor,因為只顯示一個項目。
所以它看起來像:
theItem = {name: "Name 1"} // what the service returns
<div>{{ theItem.name }}</div>
顯示所有項目時一切都很好,但當我點擊單個項目時,OnInit被調用兩次,我在platform-browser.umd.js中出錯,這在模板中確實是一個錯誤,因為它說它不能讀取undefined
的屬性name
(即theItem)。
我通過將單個項目的模板更改為:
<div>{{ theItem?.name }}</div>
起初我以為問題是模板在數據從服務加載之前呈現,所以添加?
固定它。 但是,在ngOnInit完成后,模板是否應該加載? 我的問題是,為什么要添加?
修復此問題,即使我在加載所有項目時在第一個模板中不需要它?
謝謝。
因為get
是異步的,所以它確實在加載數據之前開始渲染模板。 它將啟動服務調用並且不會等待,它將繼續處理。 添加?
允許它undefined
,然后在加載數據后適當渲染。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.