[英]How to bind data from HttpClient in angular 6?
我正在使用此方法來獲取數據:
home.service.ts
getHomes(): Observable<HomeApi> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'token': `${this.global.token}`
})
};
return this.http.get<HomeApi>('url', httpOptions);
}
home.component.ts
ngOnInit() {
this.service.getHomes().subscribe((res: HomeApi) => this.home = {
images: res['images']
});
}
home.component.html
<div *ngFor="let item of home.images">{{item.name}}</div>
現在item.name
良好,但在控制台中拋出此錯誤:
錯誤TypeError:無法讀取未定義的屬性“圖像”
這是樣本
因為你的getHomes
調用是異步的 ,所以Angular會在分配之前嘗試渲染home.images
的內容。 發生這種情況后, home.images
會在您的代碼中分配並觸發更改檢測周期,最終*ngFor
您的*ngFor
成功運行。
處理此問題的一種方法是使用以下內容:
<div *ngIf="home">
<div *ngFor="let item of home.images">{{item.name}}</div>
</div>
這只是確保home
沒有undefined
嘗試處理之前*ngFor
,這將解決您的控制台錯誤。
另一種選擇是使用安全導航操作符 :
Angular安全導航操作符(?。)是一種流暢且方便的方法,可以防止屬性路徑中的null和undefined值。
這就像添加一個簡單?
home
:
<div *ngFor="let item of home?.images">{{item.name}}</div>
你可能沒有初始化home
。 所以你第一次初始化home就在這里:
this.home = {
images: res['images']
}
在此之前*ngFor
在異步請求完成並初始化home
之前查找undefined
home
對象中的項目。
嘗試在組件頂部初始化home:例如home: any = {};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.