how to show loading indicator on page loading in angular 7 until all apis response?

谁都会走 提交于 2019-12-03 08:49:53

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

}

Another way to achieve this if you don't want to use forkJoin or want to control each one individually, you can create a Subscription variable for each API call, and then in your HTML use an *ngIf="sub1 || sub2 || ... || sub5" to display and hide the loading indicator, it will be something like this:

//declare subscriptions like so
sub1: Subscription; 

ngInit() {
  sub1 = this.api1();
  sub2 = this.api2();
  sub3 = this.api3();
  sub4 = this.api4();
  sub5 = this.api5();
}

in your HTML loading bar tag add:

*ngIf="sub1 || sub2 || sub3 || sub4 || sub5"

You can simply use a variable(s) to store API results then load the content based on it's existance:

<div *ngIf = "apiResults; else elseBlock">
    ...
</div>
<ng-template #elseBlock>Loading...</ng-template>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!