angular中的 登录检查 和 过期Session清理

时间:2023-03-08 16:20:12

angular利用ui-router进行登录检查

SAP都会有这个问题,session过期或者页面被刷新的情况下应该进入登录页.

监听ui-router的satte事件可以实现当state切换的时候检查登录情况

监听state变化处理页面刷新

    //添加事件监听
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if (toState.name == 'register') return; // 如果是进入登录界面则允许
// 如果用户不存在
if (!$rootScope.session || !$rootScope.seccion.session_id) {
event.preventDefault(); // 取消默认跳转行为
$state.go("register", { from: fromState.name, w: 'notLogin' }); //跳转到登录界面
}
});

HttpProvider的Interceptor处理过期session

intercepto拦截器,可以处理所有的请求结果,能够实现:基于状态码统一的错误处理

如何注册interceptor:https://docs.angularjs.org/api/ng/service/$http#interceptors

//register interceptor as sercice
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);
}
};
}]); //push interceptor to interceptor list
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('UserInterceptor');
}); $rootScope.$on('userIntercepted',function(errorType){
// 跳转到登录界面,这里我记录了一个from,这样可以在登录后自动跳转到未登录之前的那个界面
$state.go("login",{from:$state.current.name,w:errorType});
});

相关

UI-State Events

$stateChangeCancel

$stateChangeError

$stateChangeStart

$stateChangeSuccess

$stateNotFound

Directive Hooks

angular中的 登录检查 和 过期Session清理

详情:https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks

angular.module('do-check-module', [])
.component('app', {
template:
'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
'Date: {{ $ctrl.date }}' +
'<test date="$ctrl.date"></test>',
controller: function() {
this.date = new Date();
this.month = this.date.getMonth();
this.updateDate = function() {
this.date.setMonth(this.month);
};
}
})
.component('test', {
bindings: { date: '<' },
template:
'<pre>{{ $ctrl.log | json }}</pre>',
controller: function() {
var previousValue;
this.log = [];
//hook here
this.$doCheck = function() {
var currentValue = this.date && this.date.valueOf();
if (previousValue !== currentValue) {
this.log.push('doCheck: date mutated: ' + this.date);
previousValue = currentValue;
}
};
}
});

参考:

https://ui-router.github.io/docs/latest/modules/ng1_state_events.html

https://github.com/angular-ui/ui-router/wiki#state-change-events

http://www.brafox.com/post/2015/javascript/angularjs/angularjs-router-interceptor.html