我在一个页面中有 5 个 api 调用。有些 api 需要 20 秒才能给出响应。有些需要 30 秒才能给出响应。有些需要 10 秒,因此,当第一个 api 给出响应时,第一个 api 将加载指示器设置为 false。然后加载指示器消失。但其他 api 仍在工作,我想显示加载指示器,直到五个 api 调用响应。你能给我一些完成任务的想法吗?
code:
组件.ts
loading = true;
ngInit() {
this.api1();
this.api2();
this.api3();
this.api4();
this.api5();
}
api1(){
this.loading=true;
this.apiService.api1.subscribe(response => {
loading = false;
}, error=>{
});
}
api2(){
this.loading=true;
this.apiService.api2.subscribe(response => {
loading = false;
}, error=>{
});
}
api3(){
this.loading=true;
this.apiService.api3.subscribe(response => {
loading = false;
}, error=>{
});
}
api4() {
this.loading=true;
this.apiService.api4.subscribe(response => {
loading = false;
}, error=>{
});
}
api5() {
this.loading=true;
this.apiService.api5.subscribe(response => {
loading = false;
}, error=>{
});
}
ApiService.service.ts:
api1(): any {
return this.http.get('apiurl');
}
api2(): any {
return this.http.get('apiurl');
}
api3(): any {
return this.http.get('apiurl');
}
api4(): any {
return this.http.get('apiurl');
}
api5(): any {
return this.http.get('apiurl');
}
您可以使用 rxjs forkjoin 来实现相同的目的。 Forkjoin 等待所有请求完成,并在所有 api 调用完成后返回响应。这是一个例子。
**component.ts**
isLoading: boolean;
constructor(private apiCallService: ApiSErvice) {}
ngOnInit() {
this.isLoading = true;
this.apiCallService.multipleApiCallFunction().subscribe(response => {
this.isLoading = false;
})
}
**ApiService.service.ts**
import { Observable, forkJoin } from 'rxjs';
multipleApiCallFunction() : Observable<any[]>{
const api1 = this.http.get('apiurl-1');
const api2 = this.http.get('apiurl-2');
const api3 = this.http.get('apiurl-3');
const api4 = this.http.get('apiurl-4');
return forkJoin([api1, api2, api3, api4]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)