Sending sequential Http Requests using RXJS Observables

2.5k Views Asked by At

I would to have a function which sends an http request to an endpoint giving the list of all items, and then sending a second request to get the first element on that list. The function should return the last item. I'm using the following code but the second http request is not working.

getFirstItem(): Observable<any> {
  return this.getList().pipe(concatMap(value => this.getItem(value[0].id)));
}

Using Angular 7 and rxjs 6.4.0

Any help is appreciated.

Edit: When running the following snippet, the second console log never gets called

getFirstItem(): Observable<any> {
  return this.getList().pipe(
    tap(x => console.log(x)),
    concatMap(value => this.getItem(value[0].id)),
    tap(x => console.log(x)) // never called
}
2

There are 2 best solutions below

2
On

You can use mergeMap

var result = this.getList().pipe(
  mergeMap(value =>  this.getItem(value[0].id)))
);
0
On

Your code looks fine. I just wonder how this.getItem is implemented.

Anyway here is an working example with concatMap: https://stackblitz.com/edit/rxjs-api-call-jvqj5q?file=src/app/app.component.ts

You can use mergeMap, concatMap, switchMap. All of them will work. They just behave differently regarding how the inner Observable (this.getItem) is treated when the outer observable emits (this.getList).

More info here: https://morioh.com/p/fcfea9850b90