日前參考網路上的一些文章
寫了一個閒置自動登出的功能
在本機測試上沒問題
但是在其他電腦上零星有回報使用到一半被登出的狀況
在想會不會是這幾個原因,或是根本猜錯
1.因為偵測mousemove 所以在IE Edge Chrome 都會造成瀏覽器記憶體負擔
2.引用是在畫面,用這樣方式插入
<app-inactivity-timer></app-inactivity-timer>
但是該元件的html是沒東西的,所以會不會這樣導致其實沒讀取?
所以現在用[fxHide]=“true” 這樣觀察是否有用
3.還是說根本沒寫錯,是瀏覽器的鍋? (客戶端用edge)
故想請前輩們幫忙抓藥一下
感謝
app.component.ts
@HostListener('window:keyup', [])
@HostListener('window:click', [])
@HostListener('window:wheel', [])
@HostListener('window:mousemove', [])
resetTimer() {
this.authService.notifyUserAction();
}
要倒數的網頁.html
<app-inactivity-timer></app-inactivity-timer>
inactivity-timer.html
<h5 [fxHide]="true">
閒置{{ minutesDisplay }}:{{
secondsDisplay && secondsDisplay <= 59 ? secondsDisplay : '00'
}}後將自動登出
</h5>
inactivity-timer.ts
/** 閒置登出時間請更改這參數的數字 */
endTime = 30;
minutesDisplay = 0;
secondsDisplay = 0;
unsubscribe$: Subject<void> = new Subject();
timerSubscription: Subscription;
constructor(private authService: AuthService) {}
ngOnInit() {
this.resetTimer();
this.authService.userActionOccured
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => {
if (this.timerSubscription) {
this.timerSubscription.unsubscribe();
}
this.resetTimer();
});
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
resetTimer(endTime: number = this.endTime) {
const interval = 1000;
const duration = endTime * 60;
this.timerSubscription = timer(0, interval)
.pipe(take(duration))
.subscribe(
value => this.render((duration - +value) * interval),
err => {},
() => {
this.authService.logout();
},
);
}
private render(count) {
this.secondsDisplay = this.getSeconds(count);
this.minutesDisplay = this.getMinutes(count);
}
private getSeconds(ticks: number) {
const seconds = ((ticks % 60000) / 1000).toFixed(0);
return this.pad(seconds);
}
private getMinutes(ticks: number) {
const minutes = Math.floor(ticks / 60000);
return this.pad(minutes);
}
private pad(digit: any) {
return digit <= 9 ? '0' + digit : digit;
}
}