html部分:
<div class="loading" ng-show="loading">
<div class="tishi">
<strong><i class="fa fa-spin fa-spinner fa-lg"></i></strong>
</div>
</div>
css部分:
.loading{
top: 0;
left: 0;
position: fixed;
100%;
height: 100%;
bottom:0;
opacity: 0.5;
background: black;
z-index: 1049;
}
.loading .tishi{
left: 50%;
top: 50%;
position: fixed;
z-index: 1050;
font-size: 16px;
}
js部分:(直接在拦截器里面加)
app.factory("authHttpInterceptor", ["$q", "$injector", "storage", '$rootScope', function ($q, $injector, storage, $rootScope) {
var $http = null, $state = null;
var getHttp = function () {
if (!$http) {
$http = $injector.get('$http');
}
return $http;
};
var getState = function () {
if (!$state) {
$state = $injector.get('$state');
}
return $state;
}
return {
// 拦截成功的请求
'request': function (config) {
$rootScope.loading = true;
if (sessionStorage.token) {
config.headers.Authorization = sessionStorage.token;
}
return config;
},
// 拦截失败的请求
'requestError': function (rejection) {
$rootScope.loading = false;
return $q.reject(rejection);
},
// 拦截成功的响应
'response': function (response) {
$rootScope.loading = false;
return response;
},
// 对失败的响应进行处理
'responseError': function (rejection) {
$rootScope.loading = false;
if (rejection.status == 401)
// alert('401了');
storage.remove('loginname');
storage.remove('token');
getHttp().defaults.headers.common["Authorization"] = undefined;
getState().go('login');
return $q.reject(rejection);
} else {
return $q.reject(response);
}
return $q.reject(rejection);
}
}
}]);
在app.js中注入:
.config(["$httpProvider", function ($httpProvider) {
var token = window.sessionStorage['token'];
if (token) {
$httpProvider.defaults.headers.common['Authorization'] = token;
}
$httpProvider.interceptors.push('authHttpInterceptor');
}]).run(function($rootScope, $state, $location) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
if (toState.name == 'login') return;// 如果是进入登录界面则允许
// 如果用户不存在
if (!sessionStorage['token']) {
event.preventDefault();// 取消默认跳转行为
$state.go("login");//跳转到登录界面
}
});
});