角度:实例化对象错误,无法设置属性

时间:2019-04-15 14:36:08

标签: angular typescript

所以我试图填充我的数组,但是我首先没有实例化它。

型号:

user: User = {
  firstName: "",
  lastName: "",
  adress: ""
}
order: Order = {
  OrderId: "",
  User: this.user,
  TotalPrice: 0,
  OrderItems: []

}

在这里我要填充我的订单:

    this.Identity.getMail().then(user => this.order.OrderId == user.email);
this.order.User = this.user;
this.order.TotalPrice = this.cartTotal;
this.cartItems.forEach((item, index) => {
  this.order.OrderItems[index].ProductName = item.productName,
  this.order.OrderItems[index].ProductPrice = item.price,
  this.order.OrderItems[index].ProductQuantity = item.quantity
})

我收到此错误:

CartFullComponent.html:21 ERROR TypeError: Cannot set property 'ProductName' of undefined

那么我该如何实例化order.OrderItems以便它们接受一些值?

1 个答案:

答案 0 :(得分:1)

您可以使用this.order.OrderItems.push(item)代替分配属性。

this.Identity.getMail().then(user => this.order.OrderId == user.email);
this.order.User = this.user;
this.order.TotalPrice = this.cartTotal;
this.cartItems.forEach((item, index) => {
  this.order.OrderItems.push({ 
    ProductName : item.productName, 
    ProductPrice : item.price,
    ProductQuantity : item.quantity
  });
})