0

I am trying to do something quite basic in Javascript and that is read through an xml file and push data into an array. From all the searching i have done the syntax is just this.xxx.push(itemTobePushed).

However i am getting Cannot read property 'payrules' of undefined.

Its an angular5 project with typescript

CODE

payrules = []; // Create empty array testXml(inputValue: any) { const file: File = inputValue.files[0]; const myReader: FileReader = new FileReader(); myReader.onloadend = function (e) { xmlLoader.parseString(myReader.result, function (err, response) { response.Kronos_WFC.Response.forEach(payrule => { payrule.WSAPayRule.forEach(name => { console.log('Pay Rule Name: ', name.$.Name); // This works fine and outputs a lits of payrules this.payrules.push(name.$.Name); // This fails with Cannot read property 'payrules' of undefined }); }); }); }; myReader.readAsText(file); } 
4
  • 2
    Print in the console this ;) you'll see it's not what you expect. Scopes in Javascript are often confusing at the beginning! Commented Feb 15, 2018 at 7:38
  • That means this is undefined, you can bind a new context with payrules property on each function called by forEach Commented Feb 15, 2018 at 7:38
  • 3
    Change function (err, response) to (err, response) => Commented Feb 15, 2018 at 7:38
  • OK Thanks guys for everyone's feedback. I managed to get it working by looking at this post stackoverflow.com/a/34029588/3129691 Commented Feb 15, 2018 at 9:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.