简体   繁体   中英

angular, cannot read property 'fruits' of undefined

In angular, I get the error: cannot read property "fruits" of undefined. 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). 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);
      });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM