在这种情况下使用拦截器会更好
任何时候我们想要为所有请求提供全局功能,例如身份验证、错误处理等,能够提供在所有请求传递到之前拦截所有请求的能力是很有用的服务器并从服务器返回。
angular.module('myApp')
.factory('myInterceptor',
function ($q,$rootScope) {
var interceptor = {
'request': function (config) {
$rootScope.loading = 1;
// Successful request method
return config; // or $q.when(config);
},
'response': function (response) {
$rootScope.loading = 0;
// successful response
return response; // or $q.when(config);
},
'requestError': function (rejection) {
// an error happened on the request
// if we can recover from the error
// we can return a new request
// or promise
return response; // or new promise
// Otherwise, we can reject the next
// by returning a rejection
// return $q.reject(rejection);
},
'responseError': function (rejection) {
// an error happened on the request
// if we can recover from the error
// we can return a new response
// or promise
return rejection; // or new promise
// Otherwise, we can reject the next
// by returning a rejection
// return $q.reject(rejection);
}
};
return interceptor;
});
并将其注册到配置中
angular.module('myApp')
.config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
});
来自ng-book 的示例