2016-10-27 56 views
13

這是錯誤說使用下面的代碼不能在angular2讀取未定義的屬性「推」(...)

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

全時「無法讀取屬性未定義‘推’」下面

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

在另一組件中所示,

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

回答

58

publicDeals不啓動

publicDeals: Deal[] = []; 
2

您在使用下面來初始化數組:

publicDeals: Deal[] = []; 

publicDeals: Deal[] = new Array(); 
0

如果使用AngularFire5.0 推你必須列出您的項目之前,

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

你應該看到Angularfire的更新5.0 here

0

這裏不用上述數值列

項目:數[] = [];

相關問題