您好,我的团队需要您的帮助
如果30分钟后用户未回答是或否,我需要自动关闭我的网页。
constructor(private loginService:AuthenticationService,private router: Router) {
this.setTimeout();
this.userInactive.subscribe(()=> this.cancel());
}
setTimeout() {
this.userActivity = setTimeout(() => this.userInactive.next(undefined), 300000);
}
@HostListener('window:mousemove') refreshUserState() {
clearTimeout(this.userActivity);
this.setTimeout();
}
cancel() {
var cancel = confirm("We Detected Inactivity Do you want to continue?");
if (cancel) {
return true;
} else {
this.router.navigate(['/logout']);
return false;
}
}
答案 0 :(得分:0)
在您的取消方法中...。您需要再次设置超时时间...
cancel() {
var cancel = confirm("We Detected Inactivity Do you want to continue?");
if (cancel) {
clearTimeout(this.userActivity);
this.setTimeout();
return true;
} else {
this.router.navigate(['/logout']);
return false;
}
答案 1 :(得分:0)
尝试使用本地存储
import { Injectable } from "@angular/core";
import { Router } from '@angular/router'
const MINUTES_UNITL_AUTO_LOGOUT = 60 // in mins
const CHECK_INTERVAL = 15000 // in ms
const STORE_KEY = 'lastAction';
@Injectable()
export class AutoLogoutService {
public getLastAction() {
return parseInt(localStorage.getItem(STORE_KEY));
}
public setLastAction(lastAction: number) {
localStorage.setItem(STORE_KEY, lastAction.toString());
}
constructor(private router: Router) {
this.check();
this.initListener();
this.initInterval();
localStorage.setItem(STORE_KEY,Date.now().toString());
}
initListener() {
document.body.addEventListener('click', () => this.reset());
document.body.addEventListener('mouseover',()=> this.reset());
document.body.addEventListener('mouseout',() => this.reset());
document.body.addEventListener('keydown',() => this.reset());
document.body.addEventListener('keyup',() => this.reset());
document.body.addEventListener('keypress',() => this.reset());
}
reset() {
this.setLastAction(Date.now());
}
initInterval() {
setInterval(() => {
this.check();
}, CHECK_INTERVAL);
}
check() {
const now = Date.now();
const timeleft = this.getLastAction() + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000;
const diff = timeleft - now;
const isTimeout = diff < 0;
if (isTimeout) {
localStorage.clear();
this.router.navigate(['./login']);
}
}
}