Sreejesh T S
Sreejesh T S

Reputation: 119

How can I call multiple API's on a function with Angular?

I need to call 4 different API's on a single function which is need to execute one after another as my previous API result will use the next Call as a param. For example: I have a call API for geo Ip, then I need to call an another API which I need to pass lat and long which I have got from first API call.

How can I achieve this task on angular 4?

I heard about some methods like flatmap and forkjoin. Is this method can use? (I didn't have any code as I am little bit confused).

Upvotes: 0

Views: 11692

Answers (2)

mitopalov
mitopalov

Reputation: 88

If you can use es6 you can use async and await

async makeCalls() {
try {
  let response1 = await this.http.get(firstEndpointUrl).toPromise();
  let secondEndpointUrl = 'someUrl/' + response1.json().id;
  let response2 = await this.http.get(secondEndpointUrl).toPromise();
  let thirdEndpointUrl = 'someUrl/' + response2.json().id;
  let response3 = await this.http.get(thirdEndpointUrl).toPromise();
  return response3.json();
 } catch (error) {
  // handle error
 }
}

Upvotes: 1

Jimq
Jimq

Reputation: 372

You can do something like :

  this.http.get('/api/people/1').subscribe(character => {
      this.http.get(character.homeworld).subscribe(homeworld => {
        character.homeworld = homeworld;
        this.loadedCharacter = character;
      });
    });

So here basically you are chaining the http calls. First, we request to get a user from /api/user/1. Once loaded we the make a second request a fetch the homeworld of that particular character. Once we get the homeworld, we add it to the character object and set the loadedCharacter property on our component, you can do similar thing for 4 https calls there.

You can do this using the mergeMap operator example :

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);

More information can be find over here

Upvotes: 1

Related Questions