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,543
  • 4
  • 31
  • 52
K.Z
  • 4,853
  • 23
  • 88
  • 206

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
  • 64,681
  • 11
  • 135
  • 134
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