Reputation: 276
I have a issue with a for-loop and promises in my angular2 project. I need to fire several method which return a promises. After the promises I want to fill a array in the class by using the Promise.all(variable).then(funtion(result){.......}; When i want to access the array with in the Promise.all the console promte the error
core.es5.js:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'item' of undefined
...
public item;
allItems = [];
public method() {
var promises = [];
this.dbService.getItem('myKey', 'table')
.then((data) => {
this.myArrayNumber = data;
for (let i = 0; i < this.myArrayNumber.length; i++) {
promises.push(this.dbService.getItem(this.epodLiefernr[i], 'lieferungen'));
}
Promise.all(promises)
.then(function (result) {
for (let i = 0; i < result.length; i++) {
this.item = result[i];
}
});
...
Why, I can't acces this.item at that point? Does anybody could give me a idee how I would solve myproblem
Upvotes: 0
Views: 759
Reputation: 5187
this.item
accesses the context of the function (result){...}
and I suppose you want the outer context.
Use arrow functions instead, therefore:
Promise.all(promises)
.then((result) => {
...
});
Upvotes: 4