How to chain Http calls in Angular2?

2019-01-01 11:05发布

问题:

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?

回答1:

You can do this using the mergeMap operator

First import the operator as follows:

import \'rxjs/add/operator/mergeMap\';

Then here is how you chain two calls:

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



回答2:

Using rxjs to do the job is a pretty good solution. Is it easy to read ? I don\'t know.

An alternative way to do this and more readable (in my opinion) is to use await/async.

Example :

async getContrat(){
    //get the customer
    const customer = await this.http.get(\'./customer.json\').toPromise();

    //get the contract from url
    const contract = await this.http.get(customer.contractUrl).toPromise();

    return contract; // you can return what you want here
}

Then call it :)

this.myService.getContrat().then( (contract) => {
  // do what you want
});

or in an async function

const contract = await this.myService.getContrat();

You can also use try/catch to manage error :

let customer;
try {
  customer = await this.http.get(\'./customer.json\').toPromise();
}catch(err){
   console.log(\'Something went wrong will trying to get customer\');
   throw err; // propagate the error
   //customer = {};  //it\'s a possible case
}


标签: http angular