How To Wait For Http Request For Returning Response With In Subscribe Method In Angular 8?
In my case ill get data but the data did not sort according to the request I want when I call the first HTTP request it first assigns value back to my array then moves to the next
Solution 1:
You need to use toPromise() in this case with await keyword. It will wait for request to complete before moving to next loop and sending new request.
var res= awaitthis.http
.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd).toPromise();
imagename.imageid = res.result;
Remember to use async keyword accordingly.
Solution 2:
Please, convert an Observable to Promise is not a good solution. The great of observables are that you can join, merge,forkjoin, swhitchMap..
In this case You should use map to create an array of observables and use forkJoin to make an unique subscribe
//create an array of observablesconst obs$=this.imagesdataarray.map(imagename =>{
const fd = new FormData();
fd.append('userID', this.userid );
fd.append('projectID', imagedata.projectid);
fd.append('id', imagename.imageid);
fd.append('formFiles', imagename.image);
returnthis.http.post('http://.....', fd)
})
//subscribe to a forkJoin of the array of observables//"res" is an array with the response to the first call, the second call..//so you can in subscribe use some like:
forkJoin($obs).subscribe((res:any[],index)=>{
this.imagesdataarray[index].response=res[index];
})
BTW, you can use directy -it's not necesary formData-
const obs$=this.imagesdataarray.map(imagename =>{
const fd = {'userID':this.userid,
'projectID':imagedata.projectid,
'id':imagename.imageid,
'formFiles':imagename.image
}
returnthis.http.post('http:...', fd)
})
Solution 3:
Here is my way:
this.imagename.imageid = awaitnewPromise<any>(resolve =>this.http.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd)
.subscribe( res => { resolve(res.result);
//imagename.imageid = res.result;}
));
// Remaining code or function call
Post a Comment for "How To Wait For Http Request For Returning Response With In Subscribe Method In Angular 8?"