响应拦截器在angularjs应用程序的配置阶段附加.您可以使用它们全局响应任何$ http请求.请注意,模板文件也使用$ http请求,因此您可能希望将拦截器中的某些请求仅过滤到您希望响应的请求.
成功使用响应拦截器需要很好地理解promises模式.
下面是一个如何使用它们的例子:
angular.module('services')
.config(function($httpProvider){
//Here we're adding our interceptor.
$httpProvider.responseInterceptors.push('globalInterceptor');
})
//Here we define our interceptor
.factory('globalInterceptor', function($q){
//When the interceptor runs, it is passed a promise object
return function(promise){
//In an interceptor, we return another promise created by the .then function.
return promise.then(function(response){
//Do your code here if the response was successful
//Always be sure to return a response for your application code to react to as well
return response;
}, function(response){
//Do your error handling code here if the response was unsuccessful
//Be sure to return a reject if you cannot recover from the error somehow.
//This way, the consumer of the $http request will know its an error as well
return $q.reject(response);
});
}
});
Run Code Online (Sandbox Code Playgroud)