这是错误说 "无法读取属性'推送'使用下面的代码时未定义"
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);
}
}
答案 0 :(得分:115)
publicDeals
未启动;
publicDeals: Deal[] = [];
答案 1 :(得分:9)
你必须使用下面的方法初始化数组:
publicDeals: Deal[] = [];
或
publicDeals: Deal[] = new Array();
答案 2 :(得分:2)
这里是数字数组:
{{1}}
答案 3 :(得分:0)
如果您使用AngularFire5.0 在推送之前,您必须列出您的项目
const afList = afDb.list('items');
afList.push({ name: 'item' });
您应该会看到Angularfire 5.0 here
的更新答案 4 :(得分:0)
将元素添加到数组时,请使用以下方法。以下代码也适用于角度7和8。
const publicDeals: Deal[] = []; //initialize the array
publicDeals.push(deal);
答案 5 :(得分:0)
配合使用
publicDeals: Deal[] = [];
我之前在初始化时遇到过同样的问题
答案 6 :(得分:0)
我的错误是我没有正确声明数组。这是
optionsArray:any[];
应该是
optionsArayy:any=[];//(missing equal to)
注意:这会创建一个“any”类型的空数组