Issue
I have an array that is always undefined inside a forEach, even when I initialize it before entering the forEach:
this.deletedPersons = new Array<PersonMasterBase>();
selectedPersons.forEach(function (value) {
let index = allPersons.findIndex(p => p.p_PersonID == value.p_PersonID);
if (index < 0)
{
return false;
}
else
{
this.deletedPersons.push(allPersons[index]);
allPersons.splice(index, 1);
}
});
Any references I find online deal with the array that is the subject of the forEach, rather than a 'third party' as in my case.
The error occurs on the line where I push to this.deletedPersons and its text is:
'TypeError: Cannot read properties of undefined (reading 'deletedPersons')\n
at http://localhost:4200/main.js:8200:30\n
at Array.forEach (<anonymous>)\n
at http://localhost:4200/main.js:8191:33\n
at http://localhost:4200/vendor.js:35305:37\n
at OperatorSubscriber._next (http://localhost:4200/vendor.js:34722:21)\n
at OperatorSubscriber.next (http://localhost:4200/vendor.js:33551:18)\n
at OperatorSubscriber.onFinalize (http://localhost:4200/vendor.js:34141:36)\n
at OperatorSubscriber.unsubscribe (http://localhost:4200/vendor.js:34761:88)\n
at OperatorSubscriber._complete (http://localhost:4200/vendor.js:34751:26)\n
at OperatorSubscriber.complete (http://localhost:4200/vendor.js:33569:18)'
Solution
The this
in forEach function is referring to the current scope(forEach) and not the class itself, so this.deletedPersons
inside forEach
means your are trying to access the deletedPersons
declared in forEach which is obviously not.
the solution to this is to whether to use arrow function as:
selectedPersons.forEach((value) => {
let index = allPersons.findIndex(p => p.p_PersonID == value.p_PersonID);
if (index < 0)
{
return false;
}
else
{
this.deletedPersons.push(allPersons[index]);
allPersons.splice(index, 1);
}
});
Or assign the this.deletedPersons
to any other variable like allPersons
maybe deletedPersonsList
Answered By - Qazi Abdurrehman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.