[Fixed] how to wait for http request for returning response with in subscribe method in angular 8?

Issue

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 API call but in this case, the data comes unsorted or did not assign the right id to my array.

this.imagesdataarray.forEach(imagedata => {
imagedata.imagesnamearray.forEach(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);


this.http
.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd)
.subscribe( async (res) => {
imagename.imageid = await res.result;
});

})
});

Solution

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= await this.http
.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd).toPromise();

imagename.imageid = res.result;

Remember to use async keyword accordingly.

Leave a Reply

(*) Required, Your email will not be published