Angular http post and wait for multiple results

944 Views Asked by At

I am using Angular 11 and I need to make a http call to an api that will execute a process.

So if I execute this call:

processData(data) {
    return this.httpClient.post('https://myurl/api/process', {
      data: data
    }, 
    { 
      headers: this.headers() 
    });
}

The api will start a process on the server side and do it's stuff.

Because this will take time I need the Angular to listen and get the different responses, for example, I could get the server to send the progress percentage.

Then Angular would know how long there's left and tell the user and hopefully not just timeout waiting for the result.

Can this be done in Angular, if so how?

2

There are 2 best solutions below

0
On BEST ANSWER

You need to use reportProgress: true to show some progress of any HTTP request. If you want to see all events, including the progress of transfers you need to use observe: 'events' option as well and return an Observable of type HttpEvent. Then you can catch all the events(DownloadProgress, Response..etc) in the component method. Find more details in https://angular.io/guide/http#listening-to-progress-events

0
On

The method post returns an observable, which can even fire multiple time. Just use your method as follows:

processData(data).subscribe((res) => {
   console.log('The server has responded with :', res);
});

console.log('While I wait for the server to respond, I keep doing more stuff');
doMoreStuff();