Show loading icon while resolving routes or changing routes

I am attempting to display a loading icon while the route resolver is fetching data from the database.

Here is what I have tried:

Main Component:

_router.events.subscribe((routerEvent: RouterEvent) => {

   if (routerEvent instanceof NavigationStart) {
      console.log("start");
      this.loading = true;

   } else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {
    console.log("end");
    this.loading = false;
  }

});

Main Component HTML:

<h1 *ngIf="loading">Loading</h1>

The loading icon is not displaying at all.

The following message is logged on every route change:

https://i.sstatic.net/WOrIX.png

Update:

Below is the output after making the following changes:

 public loading: boolean = true;

 console.log(routerEvent);

 console.log("Loading is " + this.loading);

https://i.sstatic.net/a2WEv.png

Update 2:

app.component.html:

<div class="uk-offcanvas-content">
  <h1>{{loading}}</h1>
  <h1 *ngIf="loading">Loading</h1>

  <app-root-nav></app-root-nav>

  <app-notifications></app-notifications>

  <router-outlet></router-outlet> 
</div>

app.component.ts:

import {Component, OnInit, AfterViewInit} from '@angular/core';
import {AuthenticationService} from "../../authentication/services/authentication.service";
import {Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError} from "@angular/router";

import {RouterEvent} from "@angular/router";
import UIkit from 'uikit'

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
 })

 export class AppComponent implements OnInit, AfterViewInit {

  isLoggedIn: boolean;
  public loading: boolean = true;
  UIkit: any;

  constructor(private _router: Router, private _authService: AuthenticationService) {

  _router.events.subscribe((routerEvent: RouterEvent) => {
    if (routerEvent instanceof NavigationStart) {

      this.loading = true;
      console.log(routerEvent);
      console.log("Loading is " + this.loading);

  } else if (routerEvent instanceof NavigationError || NavigationCancel || NavigationEnd) {

    this.loading = false;
  }
});
}

ngAfterViewInit() {
}

ngOnInit() {

  UIkit.notification({
    message: 'my-message!',
    status: 'primary',
    pos: 'top-right',
    timeout: 5000
  });

 }

}

Answer №1

The issue at hand may seem straightforward, but it's actually quite easy to overlook. The problem lies in the improper verification of the router event type. To correct this, your code should look like this:

else if (routerEvent instanceof NavigationError || routerEvent instanceof NavigationCancel || routerEvent instanceof NavigationEnd)

The current implementation will always return true because the second clause essentially checks if "NavigationCancel" is truthy, which it will be since it's a defined type. This causes the loading status to set to false immediately when the route resolve begins, as there are multiple intermediate router events before the final NavigationEnd event, all triggering the incorrect checking mechanism.

Here is a link to a plunk for reference: https://plnkr.co/edit/7UKVqKlRY0EPXNkx0qxH?p=preview

Answer №2

If you want to display a loading icon while the route resolver is fetching data from the database, try implementing this code:

 const router = new Router();
          router.events.subscribe(event => {
                if (event instanceof ChildActivationStart) {
                      this.loaderservice.show();
                 } else if (event instanceof ChildActivationEnd) {
                      this.loaderservice.hide();
                  }
         });
    }

Answer №3

When faced with a similar situation, I was able to resolve it by taking the following approach:

  public isLoading = true;

  constructor(private router: Router) {

  }

  public navigateToTest(): void {
    this.isLoading = true;
    this.router.navigate(['/test']).then(_ => {
      this.isLoading = false;
    });
  }

To handle navigation programmatically, I set the isLoading variable to true before initiating the routing process, and then toggle its value to false once the routing is completed.

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

Executing jQuery function after the .load() method has completed

I have a script that should trigger an action once my load() request is completed, but for some reason, the alert is not appearing. The load() request is functioning properly as I can see the content of mypage.html in the .haha div. Here is the simple code ...

Retrieve all Tableau workbooks stored on the server

I am currently working with Tableau Server and have multiple workbooks published on it. My goal is to create a dropdown list that displays all the workbook names along with their corresponding URLs. This way, when a user selects a value from the dropdown, ...

Slider - incorporating a heading onto a video with HTML styling

Is there a way to display a title on a slider when one of the slides contains a video? Here is an example code snippet: <!-- Swiper--> <div data-height="100vh" data-min-height="480px" data-slide-effect="fade" class="swiper-container swiper-s ...

Is there a way to integrate the AJAX response from JavaScript into a JavaScript function?

I am having a nightmare trying to solve this issue. I am currently working on an app using phonegap and have integrated highcharts for creating graphs. The graph displays properly, but the tooltip is not working as expected. Below is the code snippet that ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

When I attempt to animate 4 div boxes, only 2 of them are actually animated instead of all

I am currently working on a grid layout with 4 boxes and I want to add a fade effect using jQuery when hovering over them. However, at the moment only 2 of the boxes are animating. How can I make the other 2 boxes also animate? Below are snippets of my jQu ...

Steps for removing an Angular project

I set up the backend of my .NET Core application in the API folder and attempted to place the front-end in a separate folder within the same directory. The tutorial I followed did it this way, using VS Code instead of Visual Studio. However, something wen ...

How to delete a specific key-value pair from an object in React.js

There is an object stored in the state: this.state = { selectedValue: {} } Now, I am adding a property to this object as follows: if (e.currentTarget.checked) { this.setState({ selectedType: { ...this.state.selectedType, ...

Explain the form of an object using typescript without considering the categories

I'm looking to define the shape of an object in TypeScript, but I want to disregard the specific types of its fields. interface TestInterface { TestOne?: string; TestTwo?: number; TestThree?: boolean; } My approach was to define it like this: ...

Tips for importing modules without encountering errors

Currently in the process of constructing a compact website with socket.io and express. Opting for Typescript to ensure accurate type errors, then transpiling the frontend code to Javascript for seamless browser execution. Frontend code: import { io, Socke ...

Searching within an iFrame for an element using the getElementById method

Hey, I'm working with an iframe and trying to reference a CSS element that is located on the source page. Here's the iframe code: <iframe id="CPHNavBar_TBDC081D1008_frameSticky" src="/stickyserviceavailabilitycheck"></iframe> I want ...

Run a series of promises in an array one after the other without relying on async and await

Imagine having an array filled with promises. Each element in this array represents a knex.js query builder that is prepared to be executed and generates a promise. Is there a way to execute each element of this dynamically built array sequentially? let ...

Is there a way to verify if a form has unsaved modifications prior to closing ng-modal in Angular 5?

Within my modal popup, I have a registration form that resembles a form-group. The form consists of fields such as text, checkbox, and select. Should a user make changes to any of the form controls without saving, then attempt to close the modal popup, I w ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

Invoking an HTML popup within a JavaScript function

Here is a question. In my project, I have the following JavaScript function: <script type="text/javascript" language="javascript"> $(document).ready(function(){ PopUpHide(); }); function PopUpShow(popup_title, pk_post_add){ document.getEl ...

Challenges with Tab navigation in React and Ionic 5

I am facing a challenge with getting the tabs navigation to function correctly. Here is my current code: App.tsx: const App: React.FC = () => <IonApp> <IonReactRouter> <IonRouterOutlet id="main"> < ...

The malfunctioning buttons are a result of embedding PHP code within a JavaScript if-query

I am experiencing an issue where my buttons are not functioning properly, preventing me from clicking on them. All variables have been correctly assigned values. Can someone assist me in resolving this? Thank you. ?> <script> ...

Executing PHP script out of echoing system

Can you help me figure out a solution for this issue I'm facing? I need to create an alert in PHP that calls JavaScript, but my PHP code is within a textarea. Is there a way to display the script outside of the textarea without having to move the PHP ...

Rails 5 Bootstrap 3 Challenge: Unresolved Application-Wide Modal Glitch

Setting up modals for the new and edit actions in my users controller was simple, but now I want to ensure display consistency by having the user show page also appear in a modal. Currently, users access their show page through the link: <li><%= ...

Creating components and dynamic routing based on the current route

I'm in the process of creating "overview" pages for different sections within my app, each triggered from the root of that particular section. For example, localhost/hi should display the HiOverview component, And localhost/he should display the HeO ...