Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Chaining http requests

I get a RxJS Observable from an httpService which is the actual http from Angular. Now as soon as I get a postive result from that, I want to process the next http Request which I get from this.retrieve(). This is more or less concattening requests. Is there a better way of doing it?

return this.httpService.query(data) 
        .map(data => {
            if(data.status > 1)
               this.retrieve().subscribe();
            return data;
});
like image 554
Trevor Hector Avatar asked Mar 06 '17 13:03

Trevor Hector


People also ask

How will you parallelize multiple observable call?

You could use RxJS forkJoin along with Array#map to trigger multiple observables in parallel.

What is forkJoin in Angular 8?

forkJoin is an operator that takes any number of input observables which can be passed either as an array or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed), then the resulting stream will complete immediately.


1 Answers

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);
    });
like image 145
seidme Avatar answered Oct 23 '22 12:10

seidme