AngularJS中的拦截器实例详解
AngularJS中的拦截器实例详解
异步操作
有时候需要在拦截器中做一些异步操作。幸运的是,AngularJS允许我们返回一个promise延后处理。它将会在请求拦截器中延迟发送请求或者在响应拦截器中推迟响应。
下面是项目中用到的代码。
ZbtjxcApp.factory('myHttpInterceptor',['$q','$window','$location',function($q,$window,$location){
return{
//全局响应
'response':function(response){
//这里还可以利用promise做异步处理,目前不用做,好像也能满足需求
switch(response.status){
case(200):
if(response.data){
//这里可以做自己相应的处理
if(response.data.code==100100){
$window.location.href="/login.html";
}
/*elseif(response.data.code=100200){
$location.path('/unauthorized');
}*/
}
break;
case(500):
//后期在处理
console.log("服务器正忙--500");
break;
case(404):
console.log("notfound--404");
break;
default:
console.log("服务器正忙");
}
returnresponse;
}
};
}]).config(['$httpProvider',function($httpProvider){
$httpProvider.interceptors.push('myHttpInterceptor');
}]);
ZbtjxcApp.factory('pageService',['$http',function($http){
vargetPageList=function(geturl,getdata){
return$http.get(geturl,{
params:getdata
});
}
return{
getPageList:getPageList
};
}]);
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!