Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an interceptor, I faced some issues.

angular.module('app').factory('httpInterceptor', ['$q', '$rootScope',
  function ($q, $rootScope) {
    var loadingCount = 0;

    return {
      request: function (config) {
        if(++loadingCount === 1) {
          $rootScope.$broadcast('loading:progress');
        }
        return config || $q.when(config);
      },    
      response: function (response) {
        if(--loadingCount === 0) {
          $rootScope.$broadcast('loading:finish');
        }
        return response || $q.when(response);
      },    
      responseError: function (response) {
        if(--loadingCount === 0) {
          $rootScope.$broadcast('loading:finish');
        }
        return $q.reject(response);
      }
    };
  }
]).config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push('httpInterceptor');
}]);

One downside of this approach is that the

$rootScope.$broadcast('loading:finish')
is triggered after each $http call completion rather than after all calls are done. My aim is to have the event fired only once all $http calls have finished.

My constraint lies in not being able to utilize $q since the $http calls within my page originate from different directives and are not confined to a single controller.

Answer â„–1

If you need to monitor the number of pending requests for $http, you can utilize the following code snippet. In my own project, I implemented this feature to display a loading spinner.

$http.pendingRequests.length

To keep track of both successful and failed calls, consider implementing something similar to the code below:

angular.module('myApp', [])
.run(function ($rootScope){
  $rootScope.failedCalls = 0;
  $rootScope.successCalls = 0;
 })
.controller('MyCtrl', 
function($log, $scope, myService) {
 $scope.getMyListing = function(employee) {
   var promise = 
       myService.getEmployeeDetails('employees');
   promise.then(
      function(payload) { 
          $scope.listingData = payload.data;
          $rootScope.successCalls++; //Counter for success calls
      },
      function(errorPayload) {
        $log.error('failure loading employee details', errorPayload);
        $rootScope.failedCalls++; //Counter for failed calls
      });
 };
 })
 .factory('myService', function($http) {
  return {
  getEmployeeDetails: function(id) {
     return $http.get('/api/v1/employees/' + id);
  }
}
 });

In essence, I have established two root scope variables to act as counters for tracking the number of successful and failed calls. Feel free to integrate and use these counters in your application as needed.

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

The value control input does not get properly updated by ngModelChange

Having difficulty updating an input as the user types. Trying to collect a code from the user that follows this format: 354e-fab4 (2 groups of 4 alphanumeric characters separated by '-'). The user should not need to type the '-', as it ...

Is it possible for an AJAX request to return both HTML data and execute callback functions simultaneously?

Is it possible to update the content of an HTML div and call a JavaScript function with specific parameters obtained through AJAX after the completion of the AJAX request, all within a single AJAX call? ...

Retrieve and manipulate custom headers from a webview within an AngularJS app

I have implemented an angular application within a webview using the following code: WebView.loadUrl(String url, Map<String, String> additionalHttpHeaders) In order to manage the content and display it appropriately, I am maintaining a state in my ...

Date selection tool in Bootstrap showing blank field

I am currently working on implementing a bootstrap datepicker to update layer dates on my website. However, I am facing an issue where the calendar dropdown does not appear when I click on the datepicker box and instead it just shows an empty box. My goal ...

Jquery is failing to handle multiple inputs

I am currently working on a system that can handle multiple Yes/No questions. However, every time I try to submit the form, I encounter an error in the console that I cannot identify, and no data is returned from the query. Previously, I used an Array to s ...

Utilize date-fns to style your dates

Struggling to properly format a date using the date-fns library. The example date I'm trying to work with is 2021-09-20T12:12:36.166584+02:00. What am I doing wrong and what is the correct approach? Here's the code snippet I have so far: import ...

Assign the appropriate label to the HTML checkbox based on the value obtained from the function

I have managed to successfully initiate the HTML service and display the checkbox itself. However, I am facing a challenge in displaying text next to the checkbox as a label. My goal is to have this label text be the return value of a function in the .gs f ...

What could be the reason for Object.assign failing to update a key in my new object?

Function handleSave @bind private handleSave() { const { coin, balance } = this.state; console.log('coin', coin); console.log('balance', balance); const updatedCoin = Object.assign({ ...coin, position: balance }, coi ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

Increased wait time during initial execution

Currently facing an issue with delaying the first run of a function. I've developed a basic slideshow that is causing problems due to this delay in the initial run. My goal is to have the first run wait for 10 seconds and then maintain a 4-second del ...

Using HTML tags with AngularJS's limitTo function

How can I limit the number of characters displayed in AngularJS when dealing with text that contains HTML tags? $scope.text = "<span><h1>Example</h1><p>Special Text</p></span>" $scope.maxNumberOfChar = 10; I need to ...

Is there a way for me to view the properties within the subcomponents?

Working on a project to create a bulletin board using React, following the official documentation. Decided to consolidate all actions related to the bulletin board into one alert component called AlertC. In the Form onSubmit statement, if the title is tr ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

Scroll through the menu with ease

I am facing an issue with my menu that has 2 levels. Whenever I try to scroll down, I want the position of the Logo to change to the bottom of the menu smoothly. However, during scrolling, there is a noticeable shake in the menu movement which makes it app ...

Exploring ways to retrieve nested values from JSON data using the Instagram API and Javascript

Trying to modify the script found at https://github.com/bigflannel/bigflannel-Instafeed in order to access Instagram photos on a website. Unfortunately, the script does not currently support displaying photo comments. I attempted to make modifications that ...

The issue arises when the d3 startAngle and endAngle values are set to NaN, resulting in an

I am working with a dataset that includes the following information: { current: 5 expected: 8 gap: -3 id: 3924 name: "Forhandlingsevne" progress: "0" type: 2 } Now, I have implemented the ...

Any recommendations for building HTML in an iOS UIWebView?

When using a UIWeb view, how can I create HTML content? For example, I have some header html code. Then, I would like to include a JavaScript script and pass data to it. Once the JavaScript is injected, I want to add the remaining HTML content from a .html ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...