[英]Angular array: ERROR TypeError: Cannot read property of undefined
I am trying to display information from a web service but am getting the following error "ERROR TypeError: Cannot read property 'bu' of undefined" . 我试图显示来自Web服务的信息,但出现以下错误“错误TypeError:无法读取未定义的属性'bu'” 。 However the data that I wish to display is showing correctly.
但是,我希望显示的数据显示正确。 Here is a copy of the web service response and code.
这是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 的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 TS
ngOnInit(): void {
this.http.get<DataResponse>(this.api.getBU()).subscribe(data => {
this.vals = data;
});
}
You need to use safe navigation operator or *ngIf inorder to handle the delay of response from your asynchronous request, 您需要使用安全的导航运算符或* 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>
EDIT 编辑
As mentioned in the comment, handle the null in your ngFor and remove it in the ngModel 如评论中所述,在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>
You should use safe navigation operator for vals?.bu
. 您应该对
vals?.bu
使用安全的导航运算符。 Because you are getting vals
asynchronously. 因为您正在异步获取
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.