I have a for loop that makes one API call depending on the length of the array if the length of the array is 6 so there will be 6 API calls, the problem is that are asynchronous calls so some of them gave me errors, How can I do to every API call inside of the loop wait until its done so then can be another call?
I really want to do it with observables and not promises
This is my service where I do the call
respuestaEncuesta(respuesta:any,idEncuesta:number,idPregunta:number){
return this.http.post(this.API_URL+'api/encuestas/'+idEncuesta+'/preguntas/'+idPregunta+'/respuesta',respuesta,this.httpOptions)
}
Here is my for loop, the only thing I do in the function sends the array and then do the loop, this is on my ts and here I call the function that does the API call inside a service
for (let j=0;j < this.obj.data.length; j++){
this.userService.respuestaEncuesta(this.obj.data[j],this.id,this.auxPreguntas[j])
.subscribe(
res => {
let auxRes:any;
auxRes = res;
if(auxRes.estado == 'success'){
console.log('successful call')
}
},
err => {
console.log(err)
}
)
}
I tried with forkjoin like this but didn't work some of the requests are not sending
respuesta:any = [];
for (let j=0;j < this.obj.data.length; j++){
this.respuesta.push(this.userService.respuestaEncuesta(this.obj.data[j],this.id,this.auxPreguntas[j]))
}
forkJoin(this.respuesta)
.subscribe(
results => {
console.log(results);
}
)