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.