首页 > 解决方案 > 为什么我的角度代码抛出错误:无法读取未定义的属性?

问题描述

我从返回 JSON 对象的 Web API 获取数据,它返回正常,但是当我循环它时,它会抛出一个错误,即无法读取未定义的“客户名称”的属性。

    [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 });
        }
           }

客户服务.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);
        });
    }

}

客户列表.component.ts

export class CustomersListComponent implements OnInit {

    constructor(public service: CustomerService) {
    }

    ngOnInit() {
        this.service.getData();
    }

}

.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>

客户模式:

   export class Customer {
     CustomerID: number ;
     CustomerName: string;
     ContactNo: string;
     VehicleRegNo: string;
     fk_VehicleMakeID: number;
     VehicleModel: number;

    }

标签: c#asp.netangulartypescriptangular7

解决方案


您正在检查 *ngIf 语句中的 CustomerName,您应该检查 d.CustomerName。'd' 将始终存在,因为您正在迭代它所在的集合。但是 d.CustomerName 的未定义它是轨道。

<div *ngIf="d.CustomerName">{{d.CustomerName}}</div

应该做的伎俩。


推荐阅读