简体   繁体   中英

Angular: Instantiate object error, can't set property

So I'm trying to populate my array but I fail to instantiate it in the first place.

Model:

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

}

and here I'm trying to populate my Order:

    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
})

I am getting this error:

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

So how do I instantiate the order.OrderItems so they'll accept some values?

You can use this.order.OrderItems.push(item) instead of assign properties.

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
  });
})

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