Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'push' of undefined(…) in angular2

Tags:

angular

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);   } } 
like image 515
user824624 Avatar asked Oct 27 '16 17:10

user824624


People also ask

Can not read the property of undefined reading push?

The "Cannot read property push of undefined" error occurs when trying to call the push() method on an undefined value. Make sure the variable on which you are calling the push() method has been initialized and set to an array before calling the method.

Can't access property push history is undefined?

To fix the "Cannot read property 'push' of undefined" error with React Router, we should call the withRouter component with our route component so the history object is available in the props. import { withRouter } from "react-router"; class App extends Component { push = () => { this. props. history.

What does Cannot read property of undefined mean?

What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.


1 Answers

publicDeals is not initiated;

publicDeals: Deal[] = []; 
like image 51
kit Avatar answered Oct 05 '22 14:10

kit