Syed Matiullah
Syed Matiullah

Reputation: 7

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 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;
});

})
});

Upvotes: 1

Views: 12747

Answers (3)

Khairul Alam
Khairul Alam

Reputation: 1336

Here is my way:

   this.imagename.imageid = await new Promise<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

Upvotes: 1

Eliseo
Eliseo

Reputation: 57909

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 observables
const 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);
      return this.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
               }
      return this.http.post('http:...', fd)
  })

Upvotes: 0

Mohsin Ali
Mohsin Ali

Reputation: 101

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.

Upvotes: 3

Related Questions