无法读取angular2中undefined(…)的属性"push" [英] Cannot read property 'push' of undefined(…) in angular2
本文介绍了无法读取angular2中undefined(…)的属性"push"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是错误消息,当使用下面的代码时, "无法读取未定义的" 的属性"push"
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(…)
整体如下所示
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);
}
}
推荐答案
publicDeals
未启动;
publicDeals: Deal[] = [];
这篇关于无法读取angular2中undefined(…)的属性"push"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文