Cannot read property 'push' of undefined(…

2020-01-25 08:54发布

问题:

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

回答1:

publicDeals is not initiated;

publicDeals: Deal[] = [];


回答2:

you have to initialize array using below:

publicDeals: Deal[] = [];

or

publicDeals: Deal[] = new Array();


回答3:

Here goes the number array:

items : number[ ] = [ ];


回答4:

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



标签: angular