简体   繁体   中英

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

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

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

<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. 'd' will always be there since you are iterating through the collection it is in. But of d.CustomerName is undefined it rails.

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

should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM