Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chain HTTP calls in Angular 2?

Tags:

http

angular

I'm new to Angular 2 and HTTP Observables. I have a component which calls an HTTP service and returns an Observable. Then I subscribe to that Observable and it works fine.

Now, I want, in that component, after calling the first HTTP service, if the call was successful, to call another HTTP service and return that Observable. So, if the first call is not successful the component returns that Observable, opposite it returns Observable of the second call.

What is the best way to chain HTTP calls? Is there an elegant way, for example like monads?

like image 629
zlaja Avatar asked Dec 05 '15 11:12

zlaja


People also ask

What is the use of forkJoin in Angular?

Why use forkJoin ? This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all.


1 Answers

You can do this using the mergeMap operator.

Angular 4.3+ (using HttpClientModule) and RxJS 6+

import { mergeMap } from 'rxjs/operators';  this.http.get('./customer.json').pipe(   mergeMap(customer => this.http.get(customer.contractUrl)) ).subscribe(res => this.contract = res); 

Angular < 4.3 (using HttpModule) and RxJS < 5.5

Import the operators map and mergeMap, then you can chain two calls as follows:

import 'rxjs/add/operator/map';  import 'rxjs/add/operator/mergeMap';  this.http.get('./customer.json')   .map((res: Response) => res.json())   .mergeMap(customer => this.http.get(customer.contractUrl))   .map((res: Response) => res.json())   .subscribe(res => this.contract = res); 

Some more details here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

More information about the mergeMap operator can be found here

like image 158
TGH Avatar answered Sep 22 '22 17:09

TGH