如何在 angular 7 页面加载时显示加载指示器,直到所有 apis 响应? [英] how to show loading indicator on page loading in angular 7 until all apis response?

查看:24
本文介绍了如何在 angular 7 页面加载时显示加载指示器,直到所有 apis 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个页面中有 5 个 api 调用.一些 api 需要 20 秒才能给出响应.有些需要 30 秒才能做出回应.有些需要 10 秒,因此,当第一个 api 给出响应时,第一个 api 将加载指示符设置为 false.然后加载指示器消失.但其他 api 仍在工作我想显示加载指示器,直到五个 api 调用响应.你能给我一些完成任务的想法吗.

I have 5 api calls in a page. some apis take 20 sec to give response. some take 30 sec to give response. some take 10 sec so, when first api gives its response, first api sets loading indicator false. then loading indicator disppears. But other apis are still working I want to show loading indicator until the five api calls response. can you please give me some idea to do the task.

代码:

component.ts

component.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:

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 调用完成时返回响应.这是示例.

You can use rxjs forkjoin for the same. Forkjoin waits for all the request is complete and return the response when all the api call complete. Here is the example.

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

}

这篇关于如何在 angular 7 页面加载时显示加载指示器,直到所有 apis 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆