我发现的最佳解决方案是 jedd.ahyoung 在他的评论中解释的解决方案。
这些是步骤。
添加两个自定义工厂
angular.module('myModule.services', [])
/**
* Save application information.
*/
.factory('Application', function($log) {
return {};
})
/**
* Custom Http Interceptor for the loader.
*/
.factory('myHttpInterceptor', function($rootScope, $q, Application) {
return {
request: function(config) {
if(Application.enableLoader){
$rootScope.$broadcast('loading:show');
}
return config;
},
requestError: function(rejection) {
$rootScope.$broadcast('loading:hide');
return $q.reject(rejection);
},
response: function(response) {
$rootScope.$broadcast('loading:hide');
return response;
},
responseError: function(rejection) {
$rootScope.$broadcast('loading:hide');
return $q.reject(rejection);
}
};
});
config
在您的步骤中添加它
.config(function($httpProvider) {
//loading interceptor
$httpProvider.interceptors.push('myHttpInterceptor');
});
在您想要的时间/地点启用/禁用它
Application.enableLoader = true;
$http({
url: url,
method: "GET"
}).success(function(data){
$log.log("Data received and my loader is already closed :)");
Application.enableLoader = false;
$scope.retrieveBooks();
}).error(function(){
$log.log("Error, but my loader is already closed :)");
Application.enableLoader = false;
$scope.retrieveBooks();
});
$scope.retrieveBooks = function(){
$http({
url: url,
method: "GET"
}).success(function(data){
$log.log("Data received and my loader is not closed :(");
}).error(function(){
$log.log("Error, but my loader is not closed :(");
});
};