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); }
this;) you'll see it's not what you expect. Scopes in Javascript are often confusing at the beginning!thisis undefined, you can bind a new context with payrules property on each function called by forEachfunction (err, response)to(err, response) =>