47

this is the error saying " cannot read property 'push' of undefined " when using the code below

  let deal = new Deal(  5, 'afaf', 'dafa',5,23 ) 
  this.publicDeals.push( deal )   // gives a error saying Cannot read property 'push' of undefined(…)

The whole is shown below

export class Deal { 
  constructor(
    public id: number,
    public name: string,
    public  description: string,
    public originalPrice: number,
    public salePrice: number
      ) { }    
}

In another component,

import { Component, OnInit } from '@angular/core'; 
import { Deal } from '../deal';
import { DealService } from '../deal.service';

@Component({
  selector: 'public-deals',
  templateUrl: 'public-deals.component.html',
  styleUrls: ['public-deals.component.css']
})

export class PublicDealsComponent implements OnInit {
  publicDeals: Deal[];

  constructor(
    private dealService: DealService) {
  }

  ngOnInit(): void {    
      let deal = new Deal(  5, 'afaf', 'dafa',5,23 ) 
      this.publicDeals.push( deal )   // gives a error saying Cannot read property 'push' of undefined(…)

  }

  purchase(item){
    alert("You bought the: " + item.name);
  }
}

7 Answers 7

183

publicDeals is not initiated;

publicDeals: Deal[] = [];
Sign up to request clarification or add additional context in comments.

5 Comments

Worked for the Angular 7
Works with Angular 9 too. Waiting for the guy who tries it with Angular 10
M the one who tried with Angular 10, It's working over here, Great
It doesn't have anything to with Angular 2,3,4....Angular 12. There was a syntax error. It will work fine for every version of Angular, until and unless Angular changes its syntax for Array.
Ladies and gents... I can reassure you that it also works with Angular 14!
14

you have to initialize array using below:

publicDeals: Deal[] = [];

or

publicDeals: Deal[] = new Array();

Comments

5

Here goes the number array:

items : number[ ] = [ ];

Comments

2

Use the below approach for when you are adding the element into the array. the below code will work for all angular versions.

const publicDeals: Deal[] = []; //initialize the array
publicDeals.push(deal);

Comments

1

If you use AngularFire5.0 Before pushing you must list your items

const afList = afDb.list('items');
afList.push({ name: 'item' });

you should see the update of Angularfire 5.0 here

Comments

1

Works with

publicDeals: Deal[] = [];

I had the same issue before with the initialization

Comments

1

My mistake was I wasn't declaring the array correctly. It was

optionsArray:any[];

It should be

optionsArayy:any=[];//(missing equal to)

Note: This creates an empty Array of type "any"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.