Angular 2 – Chaining http requests

Chaining HTTP requests can be done using flatMap or switchMap operators. Say we want to make three requests where each request depends on the result of previous one:

this.service.firstMethod()
    .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
    .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
    .subscribe(thirdMethodResult => {
          console.log(thirdMethodResult);
     });

This way you can chain as much interdependent requests you want.


UPDATE:
As of RxJS version 5.5 pipeable operators were introduced and the syntax has slightly changed:

import {switchMap, flatMap} from 'rxjs/operators';

this.service
  .firstMethod()
  .pipe(
    switchMap(firstMethodResult => this.service.secondMethod(firstMethodResult)),
    switchMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
  )
  .subscribe(thirdMethodResult => {
      console.log(thirdMethodResult);
    });

Leave a Comment