Strategies for pausing loader/spinner animation until all HTTP responses are fully processed in Angular

Implementing a loaderInterceptor to handle spinner display and hiding functionality for multiple HTTP calls on a page.

Issue: Experiencing flickering behavior in the spinner between consecutive HTTP calls.

I need a solution to only display the spinner when the first HTTP call is made and hide it once all calls are completed.

Here is the code snippet for my Loader Interceptor:

@Injectable()
export class MyLoaderInterceptor implements HttpInterceptor {
    private requests = 0;
    removeloaderTime: any;

    constructor(private loaderService: LoaderService) { }
    private stop = ((req: any): void => {
        this.removeloaderTime = setTimeout(() => {
            if (this.requests > 0) {
                this.requests--;
            }

            if (this.requests === 0) {
                // Hide Loader
                // loaderService.hide()
                clearTimeout(this.removeloaderTime);
            }
        }, 2000);
    })

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        this.requests++
        // Show Loader
        // loaderService.show()
        return new Observable(observer => {
            const subscription = next.handle(req)
                .subscribe(
                    event => {
                        if (event instanceof HttpResponse) {
                            this.stop(req);
                            observer.next(event);
                        }
                    },
                    err => {
                        this.stop(req);
                        observer.error(err);
                    },
                    () => {
                        this.stop(req);
                        observer.complete();
                    });
            return () => {
                this.stop(req);
                subscription.unsubscribe();
            };
        });
    }
}

Answer №1

If your loaderService is structured in the following way:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoadingService {
  constructor() {}

  isLoading = new Subject<boolean>();
  show() {
    this.isLoading.next(true);
  }
  hide() {
    this.isLoading.next(false);
  }
}

Then, consider implementing an interceptor named LoadingService like so:

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { LoadingService } from '../utils/loading.service';
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
  constructor(public loaderService: LoadingService) {}
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this.loaderService.show();
    return next.handle(req).pipe(finalize(() => this.loaderService.hide()));
  }
}

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

No encoding specified in POST request headers

When sending an HTML page with UTF-8 encoding that contains a form, is it possible that the browser does not specify the encoding in the POST request header parameters? I decided to test this with the latest versions of Firefox 18 and Internet Explorer 9 ...

Incorporating a minute interval in Angular Material's time picker feature

In my Angular 15 project, I am working with this material component. <mat-form-field appearance="outline"> <mat-label>{{'DOCTOR_AREA.START_TIME' | translate}} </mat-label> ...

Attempting to update Typescript on Linux Mint using npm

I am currently using typescript 2.1.4 and npm version 6.7.0. Realizing that 2.1.4 is quite outdated, I decided to try and update it. Here are the steps I took, which unfortunately did not work: $ sudo npm update -g typescript $ tsc --version Vesion 2.1. ...

Prevent dividing TypeScript branded types by using the `eslint no-restricted-syntax` selector

I have defined a custom TypeScript type as follows: export type Milliseconds = number & { __type: 'milliseconds' }; and I want to restrict the usage of the division operator on this type, like so: const foo = 1 as Milliseconds; const bar = f ...

Is there a way to dynamically define the return type of a function in Typescript?

Can the variable baz be dynamically assigned the string type? type sampleType = () => ReturnType<sampleType>; // Want to return the type of any function I pass (Eg. ReturnType<typeof foo>) interface ISampleInterface { baz: sampleType; } ...

Angular 7's Singleton Service Feature

My service setup looks like this: export abstract class ILoggingService { // abstract functions here } export class LoggingService implements ILoggingService { // service implementation } export class MockLoggingService implements ILoggingServic ...

Options for the Angular build command

After reading the official Ng-Book on Angular 6, I discovered that it is possible to create an app using the following command: ng build --target=production --base-href / However, when I attempted this on a simple app that typically builds without any iss ...

Filling the text and value array using a collection of objects

Need help with populating an array of text and value using an array of objects in Angular. Below is the JSON data containing the array of objects. Declaration public AuditYearEnd: Array<{ text: string, value: number }>; Assignment - How can I assi ...

The JSX element 'SubscribeCard' does not contain any construct or call signatures

I'm looking to implement the react-subscribe-card module for handling email subscriptions in my react.js project. Below is the code snippet from my popup.tsx file: import React from "react"; import SubscribeCard from "react-subscribe-c ...

Enforce validation rules on a nested object by referencing the properties of its parent class

How can a field in a child object be validated based on properties of the parent object's structure? For example, in the given structure, only the field first.name is not required when the fields id and dateOfBirth (dob) are defined. @InputType() expo ...

Endless cycle of NGRX dispatching

I tried creating a simple ngrx project to test the store, but I encountered an infinite loop issue. Even after attempting to mimic other examples that do not have this problem. To begin with, I defined 2 class models as shown below: export interface IBookR ...

Unable to dispatch asynchronous post request

I am currently attempting to wait for a post request. I have discovered the request-promise-native package, which allows for awaiting requests. While this method is effective for GET requests, it seems to be ineffective with POST. The URL and auth hash hav ...

unable to access environment file

Recently, I delved into the world of TypeScript and created a simple mailer application. However, I encountered an issue where TypeScript was unable to read a file. Placing it in the src folder did not result in it being copied to dist during build. When I ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

Automatically convert user input to MM/DD/YYYY format in typescript as they type the date

Hello, I am currently working on a React Native app where users input their date using TextInput. As the user types, I would like to automatically format the date as MM/DD/YYYY. Here is the function I have created so far: const formatDate(value: string ...

Issue with angular oidc-client library's automaticSilentRenew functionality

I'm currently implementing oidc authentication using "oidc-client" version 1.10.1. Below is the configuration I have set up for the userManager: const settings = { authority: (window as any).__env.auth.authority, //OAuth 2.0 authorization end ...

Provide the remaining arguments in a specific callback function in TypeScript while abiding by strict mode regulations

In my code, I have a function A that accepts another function as an argument. Within function A, I aim to run the given function with one specific parameter and the remaining parameters from the given function. Here's an example: function t(g: number, ...

Filtering multiple values from a JSON array in Angular 15, separated by commas

Currently, I am implementing Angular 15 in my project. While I am able to filter a single value from the search box, my goal is to filter multiple values separated by commas. Any assistance on achieving this would be greatly appreciated. FilterPipe impor ...

Universal categories, limitations, and hereditary traits

As a newcomer to Typescript and generics, I am unsure if I have encountered a bug/limitation of Typescript or if I am missing the correct approach to achieve my desired outcome. I have a base class called Widget which is generic and holds a value of type ...

Switching from dark mode to light mode when reloading or navigating to a new page

Hello everyone. I've successfully implemented a dark mode toggle on my website, but I'm facing an issue where the mode resets whenever I navigate to a new page or refresh the current page. Can anyone help me figure out how to prevent this from ...