Angular 2 Deep Dive Promise Foreach loop

Hi,
How can I have a resolve in foreach loop (for each element of an array, try to resolve a problem)
code:
serverIntervention.forEach(function (row){
this.interventionService.getById(row.int_id).then(
(result) =>{console.log("int exist "+this.commonService.stringfyJson(result))},
(error) =>{console.log("int not exist "+this.commonService.stringfyJson(error))}
);

I have an error : Error: Uncaught (in promise): TypeError: Cannot read property ‘interventionService’ of undefined
TypeError: Cannot read property ‘interventionService’ of undefined
knowing that my service is injected correctly (I have already used it)
PS: same error with for( let row of serverIntervention)
Thank you,

Finally I create a method add all in remote service which loop correctly

Just an FYI, I’m pretty sure this is the cause. Should be

serverIntervention.forEach(row => {

serverIntervention is an array :slight_smile:

I know, but because you’re using function() {} and not the arrow functions (() => {}), this is now the function, of which serverIntervention doesn’t exist on. The only thing I changed in the previous post was the function (row) -> row =>

Along with some of the other things you’re trying to access on this

serverIntervention.forEach(function (row) {
//                         ^^^^^^^^
// Marked vars below wont be found because of the above.
// The function is replacing this with itself
	this.interventionService.getById(row.int_id).then(
	//   ^^^^^^^^^^ wont be found
		result => {
			console.log("int exist "+this.commonService.stringfyJson(result));
			//                            ^^^^^^^^^^ wont be found
		},
		error => {
			console.log("int not exist "+this.commonService.stringfyJson(error));
			//                                ^^^^^^^^^^ wont be found
		}
	);
});

Basically, to keep the meaning of this you should use arrow functions, which you really should anyway in maybe 99.99% of cases :stuck_out_tongue:

Edit: So this is how it should look

serverIntervention.forEach(row => { // <------ This
	this.interventionService.getById(row.int_id).then(
		result => {
			console.log("int exist "+this.commonService.stringfyJson(result));
		},
		error => {
			console.log("int not exist "+this.commonService.stringfyJson(error));
		}
	);
});
1 Like