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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.