I need to trigger an event when all of my $http calls are processed. I also need to know if any call has failed. I tried using the available solutions on stackoverflow such as using an interceptor.
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');
}]);
However, with this approach the $rootScope.$broadcast('loading:finish')
gets called after every $http call is completed. I want to trigger an event when all the $http calls are over.
I cannot use $q
since the $http
calls in my page belong to various directives and are not called in the same controller.
You can use below code to check the number of pending requests for $http. I am using this to show loading spinner in my project.
$http.pendingRequests.length
For keeping a track of failed and success calls you can use something like this:
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);
}
}
});
Basically I have created 2 root scope variables and using it as counters to maintain count of success and failed calls which you can use wherever you want.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments