簡體   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