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

Angular - the offspring of another element

I'm currently exploring the possibilities of identifying if a clicked element is a child of another using Angular. In jQuery, I would typically use has() for this task, but I'm unsure of the equivalent method in Angular aside from iterating throu ...

Compilation failure due to Typescript initialization issue

Encountering a TypeScript error in my IntelliJ-Idea 2017.1.1 IDE I have enabled JavaScript, NodeJS, and TypeScript Compiler. I have exhausted all solutions but the issue persists, perhaps I am missing something. Error: Initialization error (typescript ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

Automatically reconstructing local packages when changes occur

After installing a local package using npm local paths, I am looking for a way to automatically rebuild or re-install the package whenever I make changes to the file. Can anyone help me with this? I have searched online extensively but haven't come a ...

Converting the length attribute of a table to a string does not yield any

After grappling with this bug for some time now, I've come up empty-handed in my search for a solution online. Expected Outcome: Upon pressing the create row button, I anticipate a new row being added at the bottom of the table. This row should cons ...

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

Tips for transitioning from custom CSS to Material UI's CSS in JS

I came across a project where someone implemented components with custom CSS. One interesting thing I noticed was a wrapper component, similar to Material UI's Container or just a simple div with applied styles. export const Container = styled.div` ...

The data returned from the PHP backend appears to be void

Currently, I am working on a temporary email website and one of the features that I need to incorporate is retrieving the origin of the email which involves accessing the email headers. I have written the following code snippets to achieve this: PHP Backe ...

How to keep text always locked to the front layer in fabric.js without constantly bringing it to the front

Is it possible to achieve this functionality without using the following methods? canvas.sendBackwards(myObject) canvas.sendToBack(myObject) I am looking to upload multiple images while allowing them to be arranged forward and backward relative to each o ...

Correcting the invalid syntax due to EOF issue

How can we resolve the end of file error? The brackets appear to be valid based on ecma standards, but it's not clear what is missing. After using jsonlint, this error was found: *Error: Parse error on line 16: ...States" }] }]}{ "i ...

Exploring the file attributes within nw.js

I'm in the process of developing a native application using nw.js. I have included the following code snippet: <input id="fileDialog" type="file" accept=".pdf,.epub" multiple/><a id="add" href="#">Add</a> Below is my JavaScript cod ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

What is the best way to delete HTML classes that were generated by a function?

Currently, I'm immersed in the Etch A Sketch project as part of my journey through The Odin Project. Using DOM manipulation, I successfully created a grid and displayed it on the screen. Now, my aim is to allow users to resize the grid by removing the ...

ActivatedRoute not receiving the parameter value

Having trouble retrieving the parameter from the route and passing it to a function within the component which then communicates with the service. Initially tried placing the parameter retrieval in the NgInit but moved it to the constructor, still no succ ...

How can Angular 2 effectively keep track of changes in HTTP service subscriptions? Calling the method directly may result in

After making a call to the authentication service method that checks the validity of the username and password, as well as providing an authentication token, I encountered an issue. When attempting to display the value obtained from calling the getAuthData ...

Utilize inline scripts within the views of Yii2 for enhanced functionality

I stumbled upon a jQuery code online that allows for the integration of Google Maps, and I'm looking to implement it in my application to ensure accurate address retrieval. You can find the jQuery code here. Currently, I am working with yii2 Advanced ...

An error occurred when attempting to run the command npm run compile:sass, displaying the message: npm ERR! missing script:

Everything seems to be in place with the sass folders and files, so what could be the issue? I have my package.json file set up correctly with the following code: { "name": "starter", "version": "1.0.0", " ...

Is there a way to replicate ajaxStart and ajaxStop functions without using jQuery?

After reviewing the extensive jQuery code, I'm wondering if this task would be simple to accomplish. Any suggestions on how to approach it? I'm interested in using this not for a webpage, but for a C# application that needs to monitor ajax activ ...