我正在尝试显示来自Web服务的信息但是收到以下错误“错误类型错误:无法读取未定义的属性'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;
});
}
答案 0 :(得分:2)
您需要使用安全导航操作符或* ngIf来处理异步请求的响应延迟,
<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>
答案 1 :(得分:2)
您应该使用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>