cookie在angularJS中过期后重定向到登录页面 [英] Redirect to login page after cookie expires in angularJS

查看:126
本文介绍了cookie在angularJS中过期后重定向到登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在角度cookie过期后将用户重定向到登录页面?但是我用过angualrJS和ngCookiesCookie将在以下一分钟后过期

How to redirect user to login page after angular cookies has expired ? however i've used angualrJS and ngCookies cookies will expire after one minute as the following

$cookiesProvider.defaults.expires = new Date(now.setMinutes(now.getMinutes() + 1));`

我应该使用以下$ watch功能吗?

Am i should user $watch function as the following:

$rootScope.$watchCollection($cookies.getObject('user'), function (newVal, oldval) {

       if (newVal != oldval) {
           $rootScope.$broadcast(AuthStatus.session_timeout);
           //console.log(newVal, oldval);
        } else {
           //console.log(newVal, oldval);
       }`

推荐答案

我猜它是身份验证cookie.因此,最好在使用cookie时检查到期时间.由于性能原因,滥用观察者不是一个好主意.

I guess it is a authentication cookie. So, it is better that you check the expiration time when you gonna use the cookie. It is not a good idea to abuse of watcher because of performance.

您可以使用拦截器来做到这一点,例如:

You can do that using a interceptor, for example:

angular.module('myModule')
.config(function($httpProvider) {
     $httpProvider.interceptors.push('CookieInterceptor')
})
.factory('CookieInterceptor', function() {
     return {
          'request': function(config) {
                // check if your cookie has expired and
                // $window.location.href = '/login'
          }
     }
});

如果不在SPA上,请在服务器端执行重定向.

If are not on a SPA, perform the redirect on server-side.

这篇关于cookie在angularJS中过期后重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆