AngularJS拦截器

时间:2021-10-11 11:40:50

AngularJS是通过拦截器提供了一个全局层面对响应进行处理的途径。拦截器实际是$http服务的基础中间件,用来向应用的业务流程中注入新的逻辑,其核心是服务工厂,通过向

$httpProvider.interceptors数组中添加服务工厂,在$httpProvider中进行注册。一共有四种,两种成功拦截器,两种失败拦截器。

第一步注册拦截器:

angular.module('myApp',[])

.config(function($httpProvider){

$httpProvider.interceptors.push('myInterceptors');

});

第二步调用模块的.factory方法来创建拦截器,可以在服务中添加一种或多种拦截器:

angular.module('myApp',[])

.factory('myInterceptors',function(){

'request':function(request){

//写入拦截逻辑代码

return request;

}

});