<!-- 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;
}]);
<!-- lang: js -->
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);
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;
}
$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
if(toState.name=='login')return;// 如果是进入登录界面则允许
// 如果用户不存在
if(!$rootScope.user || !$rootScope.user.token){
event.preventDefault();// 取消默认跳转行为
$state.go("login",{from:fromState.name,w:'notLogin'});//跳转到登录界面
}
});
app.factory('UserInterceptor', ["$q","$rootScope",function ($q,$rootScope) {
return {
request:function(config){
config.headers["TOKEN"] = $rootScope.user.token;
return config;
},
responseError: function (response) {
var data = response.data;
// 判断错误码,如果是未登录
if(data["errorCode"] == "500999"){
// 清空用户本地token存储的信息,如果
$rootScope.user = {token:""};
// 全局事件,方便其他view获取该事件,并给以相应的提示或处理
$rootScope.$emit("userIntercepted","notLogin",response);
}
// 如果是登录超时
if(data["errorCode"] == "500998"){
$rootScope.$emit("userIntercepted","sessionOut",response);
}
return $q.reject(response);
}
};
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('UserInterceptor');
});
$rootScope.$on('userIntercepted',function(errorType){
// 跳转到登录界面,这里我记录了一个from,这样可以在登录后自动跳转到未登录之前的那个界面
$state.go("login",{from:$state.current.name,w:errorType});
});
// 如果用户已经登录了,则立即跳转到一个默认主页上去,无需再登录
if($rootScope.user.token){
$state.go($rootScope.defaultPage);
return;
}
var from = $stateParams["from"]; $state.go(from && from != "login" ? from : $rootScope.defaultPage);
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有