Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

code:

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:

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

    }
like image 644
Kumaresan Perumal Avatar asked Apr 27 '19 07:04

Kumaresan Perumal


1 Answers

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

}

like image 112
Yash Rami Avatar answered Oct 21 '22 23:10

Yash Rami