Search code examples
angularangular11angular12

Cannot read property 'push' of undefined in Angular 11


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

Solution

  • 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[] = [];