首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ngzone angular 7的会话超时

使用ngzone angular 7的会话超时
EN

Stack Overflow用户
提问于 2019-07-26 19:39:45
回答 1查看 427关注 0票数 0

我使用了下面的超时代码。当我登录并保持非活动状态1小时后,超时成功,用户将注销。

但是当我登录并关闭浏览器,并在1小时后返回并在浏览器中打开应用程序时,会话仍然存在,用户仍然登录。

为什么我只能在应用程序处于打开和非活动状态时才能注销,如果我关闭浏览器并在1小时后返回,为什么不能注销?

代码语言:javascript
复制
import { Router } from '@angular/router';
import { AuthenticationService } from '../_services/authentication.service';
import { Injectable, NgZone } from '@angular/core';
import { Observable } from 'rxjs';

const MINUTES_UNITL_AUTO_LOGOUT = 1 // in Minutes
const CHECK_INTERVALL = 1000 // in ms
const STORE_KEY = 'lastAction';

@Injectable({
  providedIn: 'root'
})
export class AutoLogoutService {
  isSuperadmin$ : Observable<boolean>;
    isLoggedIn$ : Observable<boolean>;
    islogin = false;

  constructor(
    private auth: AuthenticationService,
    private router: Router,
    private ngZone: NgZone
  ) {
    this.isLoggedIn$ = this.auth.isUserLoggedIn;
    this.isSuperadmin$ = this.auth.isSuperadmin;
    this.lastAction(Date.now());
    this.check();
    this.initListener();
    this.initInterval();
  }

  getlastAction() {
    return localStorage.getItem('lastaction');
  }
  lastAction(value) {
    localStorage.setItem('lastaction', JSON.stringify(value))
  }

  initListener() {
    this.ngZone.runOutsideAngular(() => {
      document.body.addEventListener('click', () => this.reset());
    });
  }

  initInterval() {
    this.ngZone.runOutsideAngular(() => {
      setInterval(() => {
    this.check();
      }, CHECK_INTERVALL);
    })
  }

  reset() {
    this.lastAction(Date.now());
  }

  check() {
    const now = Date.now();
    const timeleft = parseInt(this.getlastAction()) + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000;
    const diff = timeleft - now;
    const isTimeout = diff < 0;
    this.isLoggedIn$.subscribe(event => this.islogin = event);
    this.ngZone.run(() => {
      if (isTimeout && this.islogin) {
    this.auth.logout();
    this.router.navigate(['/admin/login']);
      }
    });
  }
}
EN

回答 1

Stack Overflow用户

发布于 2019-08-31 23:51:34

您正在使用localStorage来管理登录状态。当您关闭页面时,会话仍然存在,但超时代码停止运行。您可以切换到sessionStorage,它会将登录会话仅绑定到该选项卡。然而,这确实意味着,如果用户使用安全链接打开另一个选项卡,则必须登录。

如果您希望继续使用localStorage管理登录,另一种选择是在选项卡或浏览器关闭时触发注销。有关详细信息,请参阅How can we detect when user closes browser?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57219328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档