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

六眼飞鱼酱① 提交于 2020-08-26 15:32:01

问题


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


回答1:


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




回答2:


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
}

}



来源:https://stackoverflow.com/questions/49237272/how-can-i-call-multiple-apis-on-a-function-with-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!