0
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?

vc669
  • 561
  • 5
  • 16
  • 1
    And this is a difference between normal function and arrow function. :) Just wonder how come you used arrow first and then switch to function expression? – Yury Tarabanko Feb 09 '18 at 10:32
  • 2
    I see `=>` is already used in your code. I assume you have no idea what it does? If so recommend to read "Arrow functions". – dfsq Feb 09 '18 at 10:32
  • @dfsq, you're correct. Thanks for pointing me in the right direction. Is there advantage to not using the Arrow function? – vc669 Feb 09 '18 at 10:39
  • @vc669 You could do it with `function` too, but in this case there is no point in not using arrow function. Use `(err, result) => { `. – dfsq Feb 09 '18 at 10:40
  • It works perfectly with that. – vc669 Feb 09 '18 at 10:42

1 Answers1

1

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;
});
Martin
  • 15,820
  • 4
  • 47
  • 56