Reputation:
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?
Upvotes: 0
Views: 2660
Reputation: 15313
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;
})
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.
Upvotes: 1