Display a loading spinner while navigating between routes in Angular 6

I have recently developed a spinner component

import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';

@Component({
    selector: 'app-spinner',
    templateUrl: './spinner.component.html',
    styleUrls: ['./spinner.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class SpinnerComponent implements OnDestroy {

    public isSpinnerVisible = true;
    constructor(private router: Router) {

        this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                this.isSpinnerVisible = true;

            } else if ( event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError) {
                this.isSpinnerVisible = false;
            }
        }, () => {
            this.isSpinnerVisible = false;
        });
    }

    ngOnDestroy(): void {
        this.isSpinnerVisible = false;
    }

}

In the app.component.html file:

<router-outlet>
    <app-spinner></app-spinner>
</router-outlet>

In the spinner.component.html file:

<div class="preloader" *ngIf="isSpinnerVisible">
    <div class="spinner">
    <div class="double-bounce1"></div>
    <div class="double-bounce2"></div>
    </div>
</div>

However, I am facing an issue where the spinner is not showing, and even though some background ajax requests are still in progress, NavigationEnd event quickly triggers.

Answer №1

let showSpinner = true;
constructor(private routerService: Router) {

    this.routerService.events.subscribe(event => {
        if (event instanceof NavigationStart) {
            showSpinner = true;

        } else if ( event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError) {
            showSpinner = false;
        }
    }, () => {
        showSpinner = false;
    });
}


<router-outlet>
    <app-loader *ngIf="showSpinner === true"></app-loader>
</router-outlet>

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

Incorporate a dropdown selection option into a clickable Angular 6 table row using Bootstrap 4 styling

I am currently updating a financial account book that displays all available accounts in a table format. Each row provides essential details about a specific account, and when a user clicks on a row, Angular redirects them to a detailed view for that parti ...

Ways to retrieve the returned value from the JS FETCH API outside of its scope

As a beginner in Typescript React and the Ionic framework, I am trying to use the JS FETCH API to fetch data from a third-party source. However, I am struggling to access this fetched data outside of the fetch function. If anyone could provide some guidan ...

the process of combining arrays within an array in Angular

Is there a way to combine arrays of arrays in Angular? const b: any = []; b.push( [ { date: "2019-12-20 08:08:00" }, { date: "2019-12-20 08:08:00" }, { date: "2019-12-21 08:08:00" } ], [{ date: "2019-12-20 08:08:00" }, { date: "2019-10-2 ...

Combining Power BI with Spring Angular for Seamless Integration

I am in the process of building a web platform with Spring and Angular. One important element I want to include is Power Bi integration, allowing me to generate datasets and reports using Spring and display charts in Angular. Are there any resources or t ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...

Having trouble getting Edge browser to identify embedded blob as a valid source URL within a video tag

Having trouble using a blob as the source for a video file. Works well on Chrome and Safari, but facing issues on Edge. This code is written in TypeScript with Angular 7. On Edge mobile, it seems like a broken link is displayed. private initVideoFromBlo ...

Passing specific props to child components based on their type in a React application using TypeScript

Sorry if this question has already been addressed somewhere else, but I couldn't seem to find a solution. I'm looking for a way to pass props conditionally to children components based on their type (i.e. component type). For example, consider ...

What sets an Array apart from an Observable Array?

When working with TypeScript, how do any[] and Observable<any[])> differ from each other? What advantages and disadvantages does each one offer? ...

Troubles with the sliding feature on Bootstrap 4 Carousel

I'm encountering an issue with the bootstrap carousel as it's not sliding properly. Here is my current code: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> ...

Chromium browser experiencing issues with the functionality of Dropdown component

My issue involves a basic pie chart with a dropdown menu (created with the <select> tag) that allows users to change the data displayed on the chart. I have implemented this in Angular 6 and it works perfectly fine in Firefox. However, when I tested ...

Ensuring the correct limitation of Records within a generic function

I am currently working on defining a generic TypeScript function that can accept a Record<number, boolean> and return the same value. The challenge I am facing is ensuring that the input type remains generic and is reflected accurately in the output. ...

The binding properties of ngIf and hidden do not work properly when the condition is passed from typescript

My goal is to create a dynamic form by parsing a JSON file and binding hidden/ngIf based on a condition. I am passing the condition from the typescript file and using it in the HTML file as well. Here are the changes in my code: product.component.ts expo ...

Confirm the identity of a user by checking their email against the records stored in a MySQL database

I am currently working on creating a user verification system using email that is stored in a mySql database and utilizing express JS. The user is required to input their email before filling out any other forms. If the email is not found in the email tabl ...

Looping through the values of an Observable and subscribing to a new Observable

In this scenario, we have an Array nested within an Observable. For each value in the array, we need to make an API call, which returns another Observable. Let's simplify it with an example. How can I ensure that the variable data actually contains th ...

How can I resolve a bug in Nuxt2 when using TypeScript?

I need help with implementing code using Nuxt.js 2 option API with TypeScript. computed: { form: { get: () => this.value, set: (value) => this.$emit('input', value) } } Additionally, I am encountering the fo ...

Progress of Download in Angular using RxJs

I have successfully implemented a solution in Angular 13 / RxJs 7 for tracking download progress. To start, I created some enums: export enum RequestType { get = 'GET', post = 'POST', put = 'PUT', delete = 'DELET ...

Why is Django displaying the data I provided as the HttpResponse?

Currently, I am working on a project using Angular 8 and Django. The process involves sending data from an Angular form to Django in order to store it in a database. class NewProfileView(viewsets.ModelViewSet): queryset = NewProfile.objects.all() ...

Issue: The configuration for the rule "no-empty-interface" in .eslintrc.js is not valid

Is it acceptable to include an empty interface like the one shown below in the eslintrc.js file? interface RoutesProps {} https://i.sstatic.net/HwroT.png https://i.sstatic.net/pUKhC.png ...

Preserve the data transmitted by rxjs operators

I need help with a subject that I have defined as follows: this.checkListSubject .pipe( takeUntil(this._unSubscribeAll), filter((filter) => !!filter), switchMap((index) => this._api.get('getMyData')), tap((list) => this ...