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);
  }
ccocker
  • 1,146
  • 5
  • 15
  • 39
  • 2
    Print in the console `this` ;) you'll see it's not what you expect. Scopes in Javascript are often confusing at the beginning! – sjahan Feb 15 '18 at 07:38
  • That means `this` is undefined, you can bind a new context with payrules property on each function called by forEach – CodeLover Feb 15 '18 at 07:38
  • 3
    Change `function (err, response)` to `(err, response) => ` – Aleksey L. Feb 15 '18 at 07:38
  • OK Thanks guys for everyone's feedback. I managed to get it working by looking at this post https://stackoverflow.com/a/34029588/3129691 – ccocker Feb 15 '18 at 09:54

0 Answers0