I'd like to be able to set up an AngularJS http interceptor which will set $rootScope.loading
to true
or false
, depending on whether an AJAX request is currently ongoing.
So far I've put the following together:
angular.module('myApp')
.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('loadingInterceptor');
var loadingFunction = function (data, headersGetter) {
$rootScope.loading = true
return data;
};
$httpProvider.defaults.transformRequest.push(loadingFunction);
})
.factory('loadingInterceptor', function ($q, $window, $rootScope) {
return function (promise) {
return promise.then(function (response) {
$rootScope.loading = false;
return response;
}, function (response) {
$rootScope.loading = false;
return $q.reject(response);
});
};
});
But I'm unable to inject $rootScope
into the config block, so I have no way of setting the $rootScope.loading
variable when an HTTP request begins.
Am I missing something here? How should I do this?