0

I have some code which is reading xml then parsing the data.

So here's the code:

data = [];

  ngOnInit() {
  this.myService.getData().subscribe(XMLResult => {
    const parseString = require('xml2js').parseString;
    parseString(XMLResult, function (err, result) {
       console.dir(result.listResponse.instance); // Returns Array
       this.data = result.listResponse.instance; // Here's the line giving me the error
    });

 });
}

Console.log is returning the data like this:

Array(10)
  0:
   $: {id: "23" name: "name 1"}
  1:
   $: {id: "45" name: "name 2"}

etc

How can I fix this problem?

  • 1
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Joe Clay Apr 27 '18 at 10:13

1 Answers1

1

In your current approach, this does not refer to your component anymore.

Modify your callback to use an arrow function, so that you don't lose the scope:

parseString(XMLResult, (err, result) => {
  console.dir(result.listResponse.instance);
  this.data = result.listResponse.instance;
})

Docs

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

Pankaj Parkar
  • 127,691
  • 20
  • 213
  • 279
bugs
  • 11,481
  • 5
  • 35
  • 48