繁体   English   中英

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

[英]Angular: Instantiate object error, can't set property

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

模型:

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以便它们接受某些值?

您可以使用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
  });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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