[英]angular, cannot read property 'fruits' of undefined
在 angular 中,我收到錯誤:無法讀取未定義的屬性“水果”。 在我的課堂上,我有:
export class myClass implements OnInit {
fruits: any[];
doSomething() {
this.myArray.forEach(function(m) {
const my = { test: true };
this.fruits.push(my);
}
}
我可能有不同的類型要添加到我的數組中,所以我沒有定義接口。 這是什么原因造成的?
如果你想訪問它,你應該使用箭頭函數:
fruits: any[] = [];
doSomething() {
this.myArray.forEach(m => {
const my = { test: true };
this.fruits.push(my);
}
}
箭頭函數將使其在詞法上有界,允許您從對象上下文本身(“外部”范圍)訪問this
。 在此處閱讀更多相關信息。
你必須初始化水果
export class myClass implements OnInit {
public myArray: string[] = ['banana', 'Apple, 'Kumquat']
public fruits: {test: boolean}[] = [];
constructor() {}
ngOnInit() {}
public doSomething(): void {
let my: any = {};
this.myArray.forEach( m => {
my = { test: true };
this.fruits.push(my);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.