【问题标题】:Why my angular code throw error: cannot read the property of undefined?为什么我的角度代码抛出错误:无法读取未定义的属性?
【发布时间】:2019-05-22 13:18:21
【问题描述】:

我从返回 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 });
        }
           }

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;

    }

【问题讨论】:

  • 首先检查d ,然后检查CustomerName,即:ngIf="d &amp;&amp; CustomerName"

标签: c# asp.net angular typescript angular7


【解决方案1】:

尝试在

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

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

【讨论】:

    【解决方案2】:

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

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

    应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2020-09-02
      • 2023-03-29
      • 2018-08-10
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      相关资源
      最近更新 更多