快速学习AngularJs HTTP响应拦截器
任何时候,如果我们想要为请求添加全局功能,例如身份认证、错误处理等,在请求发送给服务器之前或服务器返回时对其进行拦截,是比较好的实现手段。
angularJs通过拦截器提供了一个从全局层面进行处理的途径。
四种拦截器
实现request方法拦截请求
request:function(config){
//dosomethingonrequestsuccess
returnconfig||$q.when(config);
}
该方法会在$http发送请求后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(requestconfigurationobject)作为参数,然后必须返回配置对象或者promise。如果返回无效的配置对象或者promise则会被拒绝,导致$http调用失败。
实现requestError方法拦截请求异常
requestError:function(rejection){
//dosomethingonrequesterrorreturn$q.reject(rejection);
}
有时候一个请求发送失败或者被拦截器拒绝了,请求异常拦截器会俘获那些被上一个请求拦截器中断的请求。它可以用来恢复请求或者有时可以用来撤销请求之前所做的配置,比如说关闭进度条,激活按钮和输入框什么之类的。
实现response方法拦截响应
response:function(response){
//dosomethingonresponsesuccess
returnresponse||$q.when(response);}
该方法会在$http接收到从后台过来的响应之后执行,因此你可以修改响应或做其他操作。该方法接收响应对象(responseobject)作为参数,然后必须返回响应对象或者promise。响应对象包括了请求配置(requestconfiguration),头(headers),状态(status)和从后台过来的数据(data)。如果返回无效的响应对象或者promise会被拒绝,导致$http调用失败。
实现responseError方法拦截响应异常
responseError:function(rejection){
//dosomethingonresponseerrorreturn$q.reject(rejection);
}
有时候我们后台调用失败了,也有可能它被一个请求拦截器拒绝了或者被上一个响应拦截器中断了。在这种情况下,响应异常拦截器可以帮助我们恢复后台调用。
拦截器核心
拦截服务工厂
varapp=angular.module("ajaxHttp",[]);
app.factory("httpInterceptor",["$q","$rootScope",function($q,$rootScope){
return{
request:function(config){
//dosomethingonrequestsuccess
returnconfig||$q.when(config);
},
requestError:function(rejection){
//dosomethingonrequesterror
return$q.reject(rejection)
},
response:function(response){
//dosomethingonresponsesuccess
returnresponse||$q.when(response);
},
responseError:function(rejection){
//dosomethingonresponseerror
return$q.reject(rejection);
}
};
}]);
注册拦截工厂方法
app.config(["$httpProvider",function($httpProvider){
$httpProvider.interceptors.push("httpInterceptor");
}]);
示例
对401,404的拦截处理
app.config(["$httpProvider",function($httpProvider){
$httpProvider.interceptors.push('httpInterceptor');
}]);
app.factory("httpInterceptor",["$q","$injector",function($q,$injector){
return{
"responseError":function(response){
if(response.status==401){
varrootScope=$injector.get('$rootScope');
varstate=$injector.get('$rootScope').$state.current.name;
rootScope.stateBeforLogin=state;
rootScope.$state.go("login");
return$q.reject(response);
}
elseif(response.status===404){
console.log("404!");
return$q.reject(response);
}
}
};
]);
以上内容给大家分享快速学习AngularJsHTTP响应拦截器的相关知识,希望大家喜欢,同时感谢大家一直以来对毛票票网站的支持。