Guide to adding a loading spinner into your Angular project

I've been attempting to incorporate a spinner into my application, but unfortunately, the spinner isn't showing up.

Despite checking the console and terminal for errors, there doesn't seem to be any indication as to why the spinner is not appearing.

loader.service.ts

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

@Injectable()
export class LoaderService {
public status: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

display(value: boolean) {
    this.status.next(value);
}
}

app.module.ts

I imported LoadService and included it in the providers array.

app.component.ts

import { LoaderService } from './services/loader.service';

export class AppComponent {
  //for the spinner
  showLoader: boolean;
  //LoaderService is for the spinner
  constructor(private loaderService: LoaderService) { }
  //for the spinner
  ngOnInit() {
    this.loaderService.status.subscribe((val: boolean) => {
      this.showLoader = val;
    });
  }
}

app.component.html

<router-outlet>
<div *ngIf="showLoader">
<mat-spinner></mat-spinner>
</div>
</router-outlet>

custom.component.ts

import { LoaderService } from '../services/loader.service';

export class SurveyresultsComponent implements OnInit {

 constructor(private loaderService: LoaderService) { }

 ngOnInit() {
  //http call starts
  this.loaderService.display(true);
  //http call ends
  this.loaderService.display(false);
 }
}

Answer №1

It seems that there may be an issue with how you are calling your loader service.

The logic for your loader code appears to be:

this.loaderService.display(true);
//http call ends
this.loaderService.display(false);

This code is located in custom.component.ts, while the corresponding HTML code is in app.component.html.

You can either use the same HTML code in custom.component.html or add the following logic to app.component.ts:

this.loaderService.display(true);
//http call ends
this.loaderService.display(false);

Alternatively, you could display the value of showLoader next to the corresponding div in app.component.html like this: {{showLoader}}

Answer №2

Seems like the issue here is related to scope. In order for the subscribe function to access the component's variables, an instance of the AppComponent must be present. The 'this' keyword pertains to the scope of the subscribe function.

export class AppComponent {
    //spinner visibility
    showLoader: boolean;
    
    constructor(private loaderService: LoaderService) { }
    
    ngOnInit() {
        let self=this;

        this.loaderService.status.subscribe((val: boolean) => {
            self.showLoader = val;
        });
    }
}

Answer №3

Within your Custom.component.ts class, you have a scenario where two statements are being executed one after the other. This can be improved by implementing a timeout function.

ngOnInit() {
  // Initiating an HTTP call
  this.loaderService.display(true);
  // HTTP call completed
  
  setTimeout(() => {
            this.loaderService.display(false);
          },5000);
  
 }
 

With this adjustment in place, the spinner will now be displayed for a duration of 5 seconds.

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

I'm struggling to set up break points in both my Angular application and library within VSCode. I can only seem to get them working in either one or the other, but not both

My goal is to enable debugging in vscode for both my Angular 16 application and my library at the same time. The file structure looks like this: ./root ./root/my-app/src ./root/lib/projects/my-lib I have successfully added my lib to the app's pr ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Learn how to render a single element with multiple child elements within separate `<td>` tags in a table row using React

I'm just starting out with React and I have a code snippet that I'm using to render an HTML table in a component. Is there a more optimized way to achieve this? bodyItems = sorted.map((data) => [ data.employerName, data.sectors.map((sector ...

Using Angular to make an HTTP POST request to fetch data

My trusty .net backpack has been working flawlessly. However, I encountered an issue when trying to connect it with the Angular front end. All backend requests are post requests and require passing an ApiKey in the body of each request. Interestingly, ever ...

Is it possible to enable autocomplete for JavaScript generated code in .proto files?

I recently created a basic .proto file with the following content: syntax = "proto3"; message Event { optional string name = 1; } After downloading and installing the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) on my local machine, ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

Is TypeScript failing to enforce generic constraints?

There is an interface defined as: export default interface Cacheable { } and then another one that extends it: import Cacheable from "./cacheable.js"; export default interface Coin extends Cacheable{ id: string; // bitcoin symbol: stri ...

Wrapping text around an image using two distinct Angular components

Can text wrap around an image in Angular even if they are in separate components? Or do the text and image have to be within the same component for this to work, regardless of whether the image is on the left or right side? https://i.stack.imgur.com/hdlxD ...

What is the best way to bring in a service as a singleton class using System.js?

I have a unique Singleton-Class FooService that is loaded through a special import-map. My goal is to efficiently await its loading and then utilize it in different asynchronous functions as shown below: declare global { interface Window { System: Sy ...

The CORS policy specified in next.config.js does not appear to be taking effect for the API request

I am currently working on a Next.js application with the following structure: . ├── next.config.js └── src / └── app/ ├── page.tsx └── getYoutubeTranscript/ └── getYoutubeTranscript.tsx T ...

The structural design of a high-capacity Angular application

Our team is currently working on a large modular Angular application, with each piece being developed by different teams within the organization. The challenge lies in assembling all these modules together into one production-ready single page application ...

Extracting the content within Angular component tags

I'm looking for a way to extract the content from within my component call. Is there a method to achieve this? <my-component>get what is here inside in my-component</my-component> <my-select [list]="LMObjects" [multiple]=&qu ...

Develop a set of matching key/value pairs using TypeScript

Looking to develop a custom data type where InputKeys will serve as the keys, and the values will be key/value pairs. The keys should correspond to InputFieldKey, with the value being a string. My current progress includes {[key: string]: string}, but I n ...

Angular 2 cleaning up subscriptions when view is destroyed

I've developed an interesting "appService" that serves as the intermediary between all my components, handling interactions like forms and navigations. This service boasts multiple event emitters to which various components subscribe for different pu ...

How to fix the error: ui-switch is not a recognized element in Angular 5?

Currently, I am attempting to utilize the ui-switch feature mentioned in this link. However, I have encountered an error: ng : ui-switch is not a known element ng : if ui-switch is An angular component then verify it's a part of this module ...

Converting Antdesign's Datepicker to Typescript

I'm having trouble figuring out how to properly annotate the dateObj parameter in the handleDateChange function that I've created. App.tsx import { useState } from 'react'; import logo from './logo.svg'; ...

Heroku local is designed to support only NodeJS applications, without any Angular framework or database connectivity

I'm currently facing two separate issues. When I run my app locally, it works fine, but it doesn't function properly on Heroku. Running "heroku local" opens the NodeJS app on localhost:5000 and connects to the local database. However, when attemp ...

What is the best way to define types for an array of objects with interconnected properties?

I need to define a type for an object called root, which holds a nested array of objects called values. Each object in the array has properties named one (of any type) and all (an array of the same type as one). Below is my attempt at creating this type d ...

How can I retrieve all values from an input number field that is created using *ngFor in Angular?

In my table, I have a list of cart products displayed with a quantity field. Users can increase or decrease the quantity using options provided. Currently, if I place an update button inside a loop, it creates separate buttons for each product. However, I ...

An issue arises when trying to access a resolved variable from UI router in a component

I am facing an issue with my UI router state that has a component attached to it: export const exchangeState = { name: 'exchange', url: '/exchange', component: ExchangeMainComponent, resolve: [ { tok ...