1
export class myclass implements OnInit {
    private outagesList;
    private outageArray;

    constructor(private outages: OutagesService){}

    ngOnInit(){
        this.outages.getOutagesList().subscribe((data) => {
            this.outagesList = data;
            this.outagesList.forEach( function (arrayItem)  
            {             
              this.outageArray.push(arrayItem["title"]);          
            });
        )
}

If i try to push the data into outageArray it is throwing ERROR TypeError: Cannot read property 'outageArray' of undefined

How can i avoid this error? I need to access this outageArray value to html.

Ramya S
  • 2,954
  • 5
  • 14
  • 24

2 Answers2

2

Use an arrow function

this.outagesList.forEach((arrayItem) => {
  this.outageArray.push(arrayItem["title"]);         
});
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
-1

Once you are using post-ES6 Javascript, functions like forEach are not likely to be your best solution. The easiest way to do this is with a for..of loop:

this.outages.getOutagesList().subscribe((data) => {
    this.outagesList = data;
    for (let arrayItem of this.outagesList)
    {             
      this.outageArray.push(arrayItem.title);          
    });
)
lonesomeday
  • 233,373
  • 50
  • 316
  • 318