[英]angular, cannot read property 'fruits' of undefined
In angular, I get the error: cannot read property "fruits" of undefined.在 angular 中,我收到错误:无法读取未定义的属性“水果”。 In my class I have:
在我的课堂上,我有:
export class myClass implements OnInit {
fruits: any[];
doSomething() {
this.myArray.forEach(function(m) {
const my = { test: true };
this.fruits.push(my);
}
}
I may have different types that I want to add to my array, so I did not define an interface.我可能有不同的类型要添加到我的数组中,所以我没有定义接口。 What is causing this?
这是什么原因造成的?
If you want to access this, you should use arrow functions:如果你想访问它,你应该使用箭头函数:
fruits: any[] = [];
doSomething() {
this.myArray.forEach(m => {
const my = { test: true };
this.fruits.push(my);
}
}
Arrow functions will cause it to be lexically bounded, allowing you to access this
from the object context itself(the 'outer' scope).箭头函数将使其在词法上有界,允许您从对象上下文本身(“外部”范围)访问
this
。 Read more about it here . 在此处阅读更多相关信息。
You must initialize the fruits你必须初始化水果
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.