完成所有api调用后,按角度执行函数

时间:2020-07-08 12:08:46

标签: angular api asynchronous service observable

下面的代码是我的组件。我在其中订阅服务中的一些API。我想在所有API成功返回数据后调用 test()函数。

ngOninit() {

functionToLoadData();
}

functionToLoadData() {
 apicall1();
apicall2();
apicall3();
apicall4();
}


apicall1(){
someapicall1.subscribe();
}
apicall2(){
someapicall2.subscribe();
}
apicall3(){
someapicall3.subscribe();
}
apicall4(){
someapicall4.subscribe();
}

test() {
 console.log('i want to call afunction after all above apis are done loading');
} 

}  ```


Here in my code the api calls are done by injecting a service where all the get calls are done and return type is observable.


I want something so that my test function is called after all these apis are successfully finished.

2 个答案:

答案 0 :(得分:0)

您可以在第一个api的订阅中调用第二个api

functionToLoadData() {
    apicall1();
}

apicall1(){
    someapicall1.subscribe(
        () => {
            apicall2();
        }
    );
}
apicall2(){
    someapicall2.subscribe(
        () => {
            apicall3();
        }
    );
}
apicall3(){
    someapicall3.subscribe();
}

或者您可以将Observables转换为Promise,然后等待响应 Angular async/await

答案 1 :(得分:0)

您可以使用forkJoin。完成所有可观察的执行后,ForkJoin将发送响应。您将收到数组响应。

Example-DEMO-单击forkJoin示例并检查控制台日志。

const observable1$ = this.httpClient.get(`https://restcountries.eu/rest/v2/name/${value1}`);


const observable2$ = this.httpClient.get(`https://restcountries.eu/rest/v2/name/${value2}`)

forkJoin([observable1$, observable2$]).subscribe((response)=>{
      // get [observable1$ response, observable2$ response] in array
})

对于您的代码,它应该类似于

apicall1(){
  return someapicall1; // assuming it will return observable.
}
apicall2(){
  return someapicall2;
}

apicall3(){
   return someapicall3;
}
apicall4(){
   return someapicall4;
}

forkJoin([this.apicall1(), this.apicall2(), this.apicall3(), this.apicall4()]).subscribe((response)=>{
          this.test();
})

test() {
 console.log('i want to call afunction after all above apis are done loading');
} 

类似地,您可以使用mergeMapconcatMap(如果您正在玩可观察)。

如果您正在玩 Promise ,则可以相应地使用Promise.all