角度数组:错误类型错误:无法读取未定义的属性



我正在尝试显示来自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;
});
}

您需要使用安全导航运算符或 *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 中的空值并在 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>

相关内容

最新更新