1

I am working on Angular2 component in which I have declare array of string and initialise same time, in this component, in one of method I trying to push data but getting error of undefined, not sure what I am missing here!

export class MyComponent implements OnInit {

    public categoryData: string[] = [];

    ngOnInit(): void {

    }

    public loadDataFromServer() {

        let MyServerData = result.data;

        MyServerData.forEach(function (item) {
            this.categoryData.push(item.BarTitle); // error here
        });
    }
}

error

ERROR TypeError: Cannot read property 'categoryData' of undefined
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
K.Z
  • 5,201
  • 25
  • 104
  • 240

2 Answers2

4

You have to use an arrow function, or you lose the this context to the new anonymous function created with the function keyword:

MyServerData.forEach((item) => {
  this.categoryData.push(item.BarTitle); // no error here
});
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
2

Use This code It will Work:

export class MyComponent implements OnInit {

public categoryData:string[] = [];

ngOnInit(): void {

}

 public loadDataFromServer() {

        let MyServerData = result.data;
        const crntData = this;
        MyServerData .forEach(function(item){
            crntData.categoryData.push(item.BarTitle); // error here
        });
    });
}
MKJ
  • 120
  • 8