为什么我的角度代码抛出错误:无法读取undefined属性?

时间:2018-12-22 11:55:49

标签: c# asp.net angular typescript angular7

我正在从Web API获取数据,该API返回一个JSON对象,返回的结果很好,但是当我循环遍历它时,它抛出一个错误,即无法读取未定义的'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

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

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;

    }

2 个答案:

答案 0 :(得分:1)

尝试从

的html代码中更改您的ngIf
<td *ngIf="CustomerName">{{d.CustomerName}}</td>

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

答案 1 :(得分:0)

您正在* ngIf语句中检查CustomerName,应在其中检查d.CustomerName。因为您要遍历集合中的集合,所以“ d”将一直存在。但是d.CustomerName是未定义的,因此会出现错误。

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

应该可以解决问题。