我在一个页面中有 5 个 API 调用。一些 api 需要 20 秒才能给出响应。有些需要 30 秒才能做出回应。有些需要 10 秒,所以当第一个 api 给出响应时,第一个 api 将加载指示器设置为 false。然后加载指示器消失。但其他 api 仍在工作我想显示加载指示器,直到五个 api 调用响应。你能给我一些完成任务的想法吗?
代码:
组件.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]);
}
关于javascript - 如何在所有 api 响应之前以 Angular 7 在页面加载中显示加载指示器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878352/