[英]Why my angular code throw error: cannot read the property of undefined?
I am getting data from web API which returns a JSON object, it returns fine but when I loop over that then it throws an error that Cannot read the property of undefined 'CustomerName'.我正在从返回 JSON 对象的 Web API 获取数据,它返回正常,但是当我遍历它时,它会抛出一个错误,即无法读取未定义的“CustomerName”的属性。
[System.Web.Http.HttpGet]
public object GetBookings(string SearchByParam = "", byte WhichRecords
= 1)
{
List<ZahidCarWash.ViewModels.BookingArrivalCancellationViewModel>
lstBookingArrivalCancellation =
BookingsRepository.SelectCustomerBookingDetailsAndroid(SearchByParam,
WhichRecords);
if (lstBookingArrivalCancellation.Count > 0)
{
return Json(new { ReturnStatusJSON = true, lstArrivalCancellation = lstBookingArrivalCancellation });
}
else
{
return Json(new { ReturnStatusJSON = false, lstArrivalCancellation = lstBookingArrivalCancellation });
}
}
Customer.service.ts客户服务.ts
export class CustomerService {
formData: Customer;
Data: Customer[];
constructor(private http: HttpClient) { }
getData() {
return
this.http.get('http://localhost:13924/api/AndroidOperations/GetBookings')
.subscribe(function(data: any) {
this.Data = data['lstArrivalCancellation'] as Customer[];
console.log(this.Data);
});
}
}
customer-list.component.ts客户列表.component.ts
export class CustomersListComponent implements OnInit {
constructor(public service: CustomerService) {
}
ngOnInit() {
this.service.getData();
}
}
.html .html
<table class="table table-hover">
<tr *ngFor="let d of service.Data | async"></tr>
<td *ngIf="CustomerName">{{d.CustomerName}}</td>
<td>Tr</td>
</table>
Customer Mode:客户模式:
export class Customer {
CustomerID: number ;
CustomerName: string;
ContactNo: string;
VehicleRegNo: string;
fk_VehicleMakeID: number;
VehicleModel: number;
}
Try to change your ngIf
in the html code from尝试在 html 代码中更改您的
ngIf
<td *ngIf="CustomerName">{{d.CustomerName}}</td>
to到
<td *ngIf="d">{{d?.CustomerName}}</td>
You're checking for CustomerName in your *ngIf statement where you should be checking for d.CustomerName.您正在 *ngIf 语句中检查 CustomerName,您应该在其中检查 d.CustomerName。 'd' will always be there since you are iterating through the collection it is in. But of d.CustomerName is undefined it rails.
'd' 将始终存在,因为您正在遍历它所在的集合。但是 d.CustomerName 是未定义的。
<div *ngIf="d.CustomerName">{{d.CustomerName}}</div
should do the trick.应该做的伎俩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.