-1

When I call my function is throwing an error. I'm trying to insert my items via a forEach in angular. Below is the code which I tried.

Console Error Logs

Ts code

sItems: SaleProduct[];

btnSale() {

let tsale = new SaleProduct();

let tcustomerId = this.postForm.get('customer').value;

console.log(this.items);

this.items.forEach(obj => {
  tsale.CustomerId = tcustomerId;
  tsale.ProductId = obj.Id;
  tsale.CostPrice = obj.CostPrice;
  tsale.SellingPrice = obj.SellingPrice;

  console.log(tsale);
  console.log(this.sItems);

  this.sItems.push(tsale);
  });
}
Mervin
  • 35
  • 1
  • 8
  • Does this answer your question? [Cannot read property 'push' of undefined(…) in angular2](https://stackoverflow.com/questions/40291187/cannot-read-property-push-of-undefined-in-angular2) – R. Richards Aug 09 '21 at 22:29
  • Initialize `sItems` inline: `sItems: SaleProduct[] = [];`. You've declared it but you haven't initialized it yet. – Matt U Aug 09 '21 at 22:57

1 Answers1

2
sItems: SaleProduct[];

This declares the object but doesn't initialize it and hence you get the error as the object is undefined.

Initialize it by the following code:

sItems: SaleProduct[] = [];
CodeWarrior
  • 5,026
  • 6
  • 30
  • 46