[英]ERROR TypeError: Cannot read property '0' of undefined | Angular 4
[英]Angular array: ERROR TypeError: Cannot read property of undefined
我試圖顯示來自Web服務的信息,但出現以下錯誤“錯誤TypeError:無法讀取未定義的屬性'bu'” 。 但是,我希望顯示的數據顯示正確。 這是Web服務響應和代碼的副本。
{
"bu": [
{
"id": 1,
"bcluster": "R03 - Information Technology",
"bsector": "P20 - CA SA",
"bgroup": "319 - ITM as a Service (passthrough)",
"bunit": "-"
},
{
"id": 2,
"bcluster": "R03 - Information Technology",
"bsector": "Q04 - Information Management & Applications",
"bgroup": "P36 - Softworks",
"bunit": "001 - Softworks Licence & Maintenanc"
}
]
}
的HTML
<ul class="list-group" *ngFor="let item of vals.bu">
<li class="list-group-item d-flex justify-content-between align-items-center">
<button type="button" class="btn btn-info">{{item.id}}</button>
<input type="text" class="input-group btn btn-light" [(ngModel)]="item.bunit">
<button type="button" class="btn btn-primary">Update</button>
</li>
</ul>
TS
ngOnInit(): void {
this.http.get<DataResponse>(this.api.getBU()).subscribe(data => {
this.vals = data;
});
}
您需要使用安全的導航運算符或* ng如果要處理來自異步請求的響應延遲,
<button type="button" class="btn btn-info">{{item?.id}}</button>
<input type="text" class="input-group btn btn-light" [(ngModel)]="item?.bunit">
<button type="button" class="btn btn-primary">Update</button>
</li>
編輯
如評論中所述,在ngFor中處理null並在ngModel中將其刪除
<ul class="list-group" *ngFor="let item of vals?.bu">
<li class="list-group-item d-flex justify-content-between align-items-center">
<button type="button" class="btn btn-info">{{item.id}}</button>
<input type="text" class="input-group btn btn-light" [(ngModel)]="item.bunit">
<button type="button" class="btn btn-primary">Update</button>
</li>
</ul>
您應該對vals?.bu
使用安全的導航運算符。 因為您正在異步獲取vals
。
<ul class="list-group" *ngFor="let item of vals?.bu">
<li class="list-group-item d-flex justify-content-between align-items-center">
<button type="button" class="btn btn-info">{{item.id}}</button>
<input type="text" class="input-group btn btn-light" [(ngModel)]="item.bunit">
<button type="button" class="btn btn-primary">Update</button>
</li>
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.