Search code examples
javascriptangularangular5xml2js

'this' is undefined in Angular, XML2JS


export class ServerComponent {
servers:string[];
getString:any;

serversJSON:any;
    constructor() {
      }
    ngOnInit() {
        console.log("ngOnInit");   
         this.getXmlService.getData().subscribe((getString) => 
        {
          xml2js.parseString(getString, function (err, result) {
            this.serverJSON = result; // This doesn't work
            console.log(result);      // This works
            });
        });
      }
}

In this code, the indicated line does not seem to be able to access this. Console logging shows an undefined. result gives me a correct and formatted JSON, but when I attempt to take the result variable and set it in the this.serverJSON, it throws an error Cannot set property 'serversJSON' of undefined. I want to take the value held in result and put it in serversJSON. How can this be achieved and why is this not available?


Solution

  • You are losing the context of this within your callback function.

    Use a fat-arrow function (which preserves this) instead.

    xml2js.parseString(getString, (err, result) => {
      this.serverJSON = result;
    });