How can I display a loading indicator in an Angular 7 application while waiting for all API responses to complete?

I have multiple API calls on a page, each with different response times. When the first API call finishes and sets the loading indicator to false, I want to keep the indicator active until all five API calls have responded. Can you provide any suggestions on how to achieve this?

Here is the code snippet:

component.ts


loading = true;
ngInit() {
  this.api1();
  this.api2();
  this.api3();
  this.api4();
  this.api5();
}

api1(){
  this.loading=true;
  this.apiService.api1.subscribe(response => {
    this.loading = false;
  }, error=>{

  });
}
api2(){
  this.loading=true;
  this.apiService.api2.subscribe(response => {
    this.loading = false;
  }, error=>{

  });

}
api3(){
  this.loading=true;
  this.apiService.api3.subscribe(response => {
    this.loading = false;
  }, error=>{

  });
}
api4() {
  this.loading=true;
  this.apiService.api4.subscribe(response => {
    this.loading = false;
  }, error=>{

  });
}
api5() {
  this.loading=true;
  this.apiService.api5.subscribe(response => {
    this.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');
 }

Answer №1

To streamline multiple API calls, you can utilize rxjs forkjoin. This method allows all requests to be completed before returning the responses. Check out the example below.

**sample-component.ts**

isLoading: boolean;
constructor(private dataService: DataAPIService) {}
ngOnInit() {
   this.isLoading = true;
   this.dataService.executeMultipleAPIRequests().subscribe(response  => {
       this.isLoading = false;
})
}


**DataAPIService.service.ts**

import { Observable, forkJoin } from 'rxjs';

executeMultipleAPIRequests(): 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]);

}

Answer №2

While this question may not be currently active, I wanted to provide the solution here for anyone who may need it in the future.

An angular package can be used to display a spinner (loader) whenever an API call is made. This is particularly useful for displaying the spinner during the initial load process. Additionally, regex patterns, methods, and headers can be utilized to filter the APIs.

https://www.example.com/ng-spinner-package

Answer №3

If you're looking for an alternative to using forkJoin or if you prefer more control over each API call individually, one approach is to create a Subscription variable for each API call. Then, in your HTML code, you can use *ngIf="sub1 || sub2 || ... || sub5" to toggle the visibility of the loading indicator. Here's how you can implement this:

// Define subscription variables
sub1: Subscription; 

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

In your HTML code for the loading bar tag, include:

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

Answer №4

To efficiently handle API responses, consider storing the data in variable(s) and dynamically loading content based on its availability:

<div *ngIf = "apiData; else loadingBlock">
    ...
</div>
<ng-template #loadingBlock>Loading...</ng-template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ReserveYourSpot: Effortless Seat Reservation with AngularJS at the Click of a Button [GIF]

ReserveYourSpot: An innovative AngularJS application designed to streamline the process of reserving seats for a movie show, similar to popular platforms like BookMyShow. https://i.stack.imgur.com/PZk1I.gif Interactive User Functions (Use Cases): A ...

Manipulating Object Properties in the Browser's Console

When I log a JavaScript object in the browser, my curiosity leads me to expand it in the console window. An example of this is: console.log(console); I discover what's inside, but then a thought crosses my mind. When I dig deeper and expand the obje ...

How can I fix the issue of not being able to scroll up on a page in Chrome using jQuery

When at the bottom of the page and clicking on 'Send us your resume', the intent is for the browser to scroll to the top of the page. This functionality works fine in IE and Firefox, unfortunately, it does not behave as expected in Chrome. Here& ...

unable to include Cross-Origin header in ajax request

Whenever I include the HTTP_X_REQUESTED_WITH header in my ajax requests to another server, I encounter an error stating: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.xxxxxxxxxxxx.com/checkurl.php? ...

The background color in CSS frames the text with a unique hue

Is there a way to wrap my multi-line text inside a div with a background color that automatically adjusts its size based on the text length? .multiline{ padding:0px; white-space: pre-wrap; height: 100px; width: ; margein:0px } <div style="b ...

Exploring the incorporation of various local fonts in NextJs version 13

Having trouble adding multiple local fonts to nextjs 13. According to the instructions in the documentation, you should follow these steps for a single file. I attempted to import two files like this: import '@/styles/globals.css'; import localF ...

Retrieve the row id from the table by clicking on a button in a modal box using jQuery

I am encountering a challenge with a small task due to my limited experience in jQuery. I have a table where each row has an icon. When the icon is clicked, a modal box appears with some content. After closing the modal box, I want to retrieve the table ro ...

The scroll() function in jQuery does not bubble up

Recently, I encountered an issue with a Wordpress plugin that displays popups on scroll. The code I currently have is as follows: jQuery(window).scroll(function(){ //display popup }); The problem arises with a particular website that has specific CSS ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Issues with select options not functioning correctly in knockout framework

Currently, I am engaged in a project where data is being retrieved from an API. The main task at hand is to create a dropdown list using select binding. In order to do so, I have defined an observable object to hold the selected value within my data model. ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Troubleshooting problem with scrollbar in HTML table within a div element

I'm utilizing Bootstrap for the majority of my CSS. I've split a section into two columns, with the left column displaying a table with data and the right side featuring a Google map. The issue arises when the table row grows, as it doesn't ...

JavaScript - Capture user input and store it in a cookie when the input field is changed

Any help with my issue would be greatly appreciated. I'm currently working on saving the value of a form input type="text" to a cookie when the input has changed. It seems like I'm close to getting it right, but unfortunately, it's not worki ...

Interacting across numerous tiers of nested directives

Allow me to explain the situation, it may seem a bit intricate. I have structured my directives in three layers: At the top layer, there is a popup directive In the middle layer, there is a switch-pane directive * The bottom layer consists of various vie ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...

Adjust the FlipClock time based on the attribute value

When setting up multiple FlipClock objects on a page, I need to retrieve an attribute from the HTML element. The specific HTML tag for the clock is: <span class="expire-clock" data-expire="2015-09-22"> Is there a way to access '2015-09-22&apos ...

Having trouble retrieving user data that is being passed as a context value using React's useContext

Currently, I am integrating Google login into my React application and facing an issue with passing the response data from Google login (i.e. user data) to other React components using the useContext hook. Unfortunately, I am unable to retrieve the user da ...

Shared Vue configuration settings carrying over to Jest spec files

For my unit testing of components using VueJS and Jest, I'm incorporating the Bootstrap Vue library for styling. To address console warnings regarding unknown plugins, I've set up a configuration file: import { createLocalVue } from '@vue/t ...

Three.js object changing position along the curve of a bowl

I am currently developing a threejs game. My goal is to have a ball move from the z-position of -5000 to 0. This is how I am creating the mesh: let geometry = new THREE.SphereGeometry(100, 32, 32); let material = new THREE.MeshBasicMaterial({ ...