Typescript loading icon directive

Seeking to create an AngularJS directive in TypeScript that wraps each $http get request with a boolean parameter "isShow" to monitor the request status and dynamically show/hide the HTML element depending on it (without utilizing $scope or $watch). Any suggestions on how to accomplish this? Thank you.

Answer №1

Implement the concept of the promise disposer pattern:

var spinnerSemaphore = 0;
function maintain(fn){
    spinnerSemaphore++;
    var result = $q.when(fn());
    fn().then(function(){ spinnerSemaphore--; }, 
            function(){ spinnerSemaphore--; });
    return result; 
}

This approach allows you to:

maintain(function(){
    return $http.get(...); 
});
maintain(function(){
    return $http.get(...); 
});
maintain(function(){
    return $http.get(...); 
});
maintain(function(){
    return $timeout(...); // this applies to other promises as well
});

Connect displaying the spinner to the variable spinnerSemaphore (where a value of 0 means hiding the spinner, and any value greater than 0 means showing it).

Answer №2

For those in search of a solo spinner, the task can be accomplished seamlessly by linking its visibility to ng-show (or any similar function) with $http.pendingRequests.length. This approach naturally requires access to either $http within scope or $rootScope.

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

Declaration of types for invoking the lodash `mapKeys` function

Is there a way to create a function that can map object keys from camelCase to snakeCase, and be used multiple times with different objects? I have already written a function called mapKeysToSnakeCase which does the job, but I'm curious if there is a ...

Error message thrown by Angular JS: [$injector:modulerr] – error was not caught

I have been working on a weather forecasting web application using AngularJS. Here's a snippet of my code: var myApp = angular.module("myApp", ["ngRoute", "ngResource"]); myApp.config(function($routeProvider){ $routeProvider .when('/',{ ...

When a button is clicked in (Angular), it will trigger the highlighting of another button as a result of a value being modified in an array. Want to know the

Currently in the process of developing a website with Angular, I've encountered an unusual bug. The issue arises when using an *ngFor div to generate twelve buttons. <div *ngFor = "let color of colors; let i = index" style = "display ...

Disabling dynamic color updates upon refresh

I am currently using chartjs and I want to generate new random colors each time the page is refreshed. However, I need these colors to remain fixed and not change after a page refresh or reload. Below is the function I am working with: getRandomRgb() { ...

In ReactJS with TypeScript, declaring a constant response after calling the login function using the await keyword

Currently tackling a task in React and Typescript where I am logging in as a user. Encountering an issue when trying to access the response variable, which leads to the following error: Object is of type 'unknown'.ts(2571) const response: unknow ...

Tips for preserving the Context API state when navigating between pages in Next.js

Currently, I am working on a project that involves using nextJs and TypeScript. To manage global states within my application, I have implemented the context API. However, a recurring issue arises each time I navigate between pages - my state re-evaluates ...

Exploring ngModel components with a specified class

In my HTML code, I've assigned many elements with ngModel defined as ng-model = "object.[something]". For example: <div class="form-group row" ng-model="object.askUser"> I use this method to keep my purpose clear for these elements. My questi ...

An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution useAudio.tsx import { useEffect, useRef } from 'react'; type Options = { volume: number; playbackRate: num ...

Is it possible to execute an AngularJS project without using Gruntjs?

Is it possible to run my AngularJS project without Gruntjs? If so, could you please provide instructions on how to do so? I am running the project on a windows machine and have already installed node.js and eclipse mars 4.5. ...

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

Display the message "Please complete all required fields" on the AngularJS href when the necessary fields have not been filled out

Is there a way to implement input validation so that when a user clicks on a href link without filling out the required input fields, they see a message prompting them to fill in the fields? I tried changing the href to a button and it worked, but that&apo ...

Is there a way to locate all projects impacted by `nx`?

Currently, I am utilizing the nx tool to manage a mono repo specifically designed for typescript projects. The nx comes equipped with a command called affected, which allows me to focus solely on the changed project and any other projects that rely on it. ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

Combining Bazel, Angular, and SocketIO Led to: Unforeseen Error - XMLHttpRequest Not Recognized as Constructor

I am looking to integrate ngx-socket-io into my Angular application. I utilize Bazel for running my Angular dev-server. Unfortunately, it seems that ngx-socket-io does not function properly with the ts_devserver by default. Upon checking the browser consol ...

TS Mapped Type: Dynamically exclude specific keys based on their values

Seeking a method to create a mapped type that excludes specific keys based on the value of the mapped key. For instance: Consider an option: Options struct, where Options is a union type defined as: { type: DataType } or { type: DataType, params: DataPar ...

Guide on including the angular value (id) in conjunction with repeating data-target for executing a function

I have the following code snippet. Now, I am trying to pass a dynamic AngularJS variable, specifically the id of a repeating list. The button in question is used for deactivation purposes, and upon clicking it, a confirmation box pops up. Upon confirming ...

Encountering an unexpected termination error when using Typescript, pg, Express, and Psql within a Docker container: "Error: Connection terminated unexpectedly"

I am facing an issue with connecting to my database running on a Docker container using a postgres image: docker run --name postgres-container -p 2345:2345 -e POSTGRES_PASSWORD=password123 -e POSTGRES_USER=admin -d postgres The TypeScript code I have is i ...

Transferring data between two screens within an Ionic app by harnessing the power of angularJS

As a beginner in Ionic and Angular development, I am currently facing an issue with my Ionic application. I have two pages - one with drop-down selects and a submit button, and another page to process the user's choices and display the results. The pr ...

Having trouble getting the basic example of Angular UI-Router to work? Check out the complete code on Plunker for assistance

Having trouble with Angular UI-Router? Check out my code snippet on Plunker. I'm attempting to set up a simple routing example in AngularJS. However, the welcomeView.html isn't displaying on the page. (function() { "use strict" var app = an ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...