$httpAngularJS 的 $http 服务允许我们通过发送 HTTP 请求方式与后台进行通信。在某些情况下,我们希望可以俘获所有的请求,并且在将其发送到服务端之前进行操作。还有一些情况是,我们希望俘获响应,并且在完成完成调用之前处理它。一个很好例子就是处理全局 http 异常。拦截器(Interceptors)应运而生。本文将介绍 AngularJS 的拦截器,并且给几个有用的例子。
什么是拦截器?
$httpProvider 中有一个 interceptors 数组,而所谓拦截器只是一个简单的注册到了该数组中的常规服务工厂。下面的例子告诉你怎么创建一个拦截器:
<!-- lang: js -->module.factory('myInterceptor', ['$log', function($log) { $log.debug('$log is here to show you that this is a regular factory with injection'); var myInterceptor = { .... .... .... }; return myInterceptor;}]);
然后通过它的名字添加到 $httpProvider.interceptors 数组:
<!-- lang: js -->module.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('myInterceptor');}]);
拦截器允许你:
angularJs提供四种拦截器,其中两种成功拦截器(request、response),两种失败拦截器(requestError、responseError)。
angular.module("myApp", []) .factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) { var httpInterceptor = { 'responseError' : function(response) { ...... return $q.reject(response); }, 'response' : function(response) { ...... return response; }, 'request' : function(config) { ...... return config; }, 'requestError' : function(config){ ...... return $q.reject(config); } } return httpInterceptor; }
新闻热点
疑难解答
图片精选