Search code examples
angularhttprxjsangular-httpclient

Angular Sequential HTTP Rest request


I have following code in Angular 8:

fetchMedia() {
    this.mediaDetails.forEach(entry => {
        this.fetchSingleMedia(entry); // NEED TO MAKE THIS SEQUENTIAL
    }
  });
}

fetchSingleMedia(entry) {

  this.mediaService.getMedia(entry).subscribe(
    (data) => {
       // MY LOGIC HERE
    },
    error => {}
  );
}

The fetchSingleMedia method is used by other parts of the code as well. I want to keep the Logic in fetchSingleMedia itself

Now, if I have to sequentially make multiple requests to fetchSingleMedia method, how do I need to modify the fetchSingleMedia method and way of calling it? maybe using async/await/promise or rxjs?

Edit:

With concat, second request is sent before first's response is received. I want second request to go after first request's response is received


Solution

  • Use concat to sequentially run an array of observables.

    From the docs:

    Subscribe to observables in order as previous completes

    Build your array of observables first, and then run them sequentially in concat.

    fetchMedia() {
      const observables = this.mediaDetails.map(entry => {
        return this.fetchSingleMedia(entry);
      });
    
      concat(...observables).subscribe(singleMedia => {
        console.log(singleMedia);
      },
      error => {
      });
    }
    
    fetchSingleMedia(entry): Observable<any> {
      return this.mediaService.getMedia(entry).pipe(
        catchError(() => of('Error')), // TODO: return simple error result here, 
        tap(mediaEntry => console.log(mediaEntry)) // TODO: any processing here
      );
    }
    

    Note that you will need to handle errors on the individual observables if you want to ignore errors. I have shown a very simplistic way to do this.

    DEMO: https://stackblitz.com/edit/angular-mhrxha