zlaja zlaja - 1 month ago 13
HTTP Question

How to chain Http calls in Angular2

I'm new to Angular2 and Http Observable. I have a component which calls Http service and returns Observable. Than I subscribe to that Observable and it works fine.

Now, I want,in that component, after calling first Http service,if call is success, call other Http service and return that Observable. So, if first call is not success the component returns that Observable, opposite it returns Observable of second call.

So, question is, what is the best way to chain Http calls? Is there any elegant way, for example like monads?

TGH TGH
Answer

You can do this using flatMap

First import the operator via import 'rxjs/add/operator/mergeMap';

Then here is how you chain two calls:

this.http.get('./customer.json').map((res: Response) => {
               this.customer = res.json();
               return this.customer;
            })
            .flatMap((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