【发布时间】:2020-10-15 14:24:38
【问题描述】:
我正在尝试完成以下操作:对于我的网络应用程序,我尝试实现一个计时器,当用户显示活动(意味着触发点击、keydown 或滚动事件)时,它会自动重置回 60 秒。我将 Observables 用于事件流。所有这一切都发生在您登录我的网络应用之后。
如果计时器用完(从 60 秒到 0),用户应该被简单地重定向到后端 URL,这会删除 cookie 并重定向回前端的登录屏幕。现在一切都很好,花花公子,超时有效,但是当我单击某些东西,滚动或单击键盘上的某些东西时,什么也没有发生。 我还想要一个检测鼠标移动的事件流,我该如何用 RxJS 做到这一点?
我的代码:
数据服务:
// login timer
public timeLeft = 60;
public interval: number;
constructor(private http: HttpClient, public datepipe: DatePipe, private cookieService: CookieService) {
}
public startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
// FIXME HTTPS implementation
window.location.href = 'http://example.com:8081/logout';
clearInterval(this.interval);
this.timeLeft = 60;
}
}, 1000);
}
public resetTimer() {
console.log('Juup');
clearInterval(this.interval);
console.log(this.timeLeft);
//this.timeLeft = 60;
//this.startTimer();
/* let time;
clearTimeout(time);
time = setTimeout(this.logout, 3000); */
}
登录逻辑:
return this.http.post<any>(`${environment.apiUrl}/api/login`, { email, password }, {withCredentials: true})
.pipe(map(user => {
// login logic here
// if everything is ok then
this.DataService.startTimer();
app.component.ts:
constructor(public authenticationService: AuthenticationService, public DataService: GlobalDataService,
private router: Router) {
const source1$ = fromEvent(document, 'click');
const source2$ = fromEvent(document, 'keydown');
const source3$ = fromEvent(document, 'scroll');
const sources$ = merge (
source1$,
source2$,
source3$
);
// map to string with given event timestamp
const example = sources$.pipe(map(event => `Event time: ${event.timeStamp}`));
// output (example): 'Event time: 7276.390000000001'
//
// const subscribe = sources$.subscribe(val => console.log(val));
const subscribe = sources$.subscribe(this.DataService.resetTimer);
interval: number;
subscribeTimer: any;
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.DataService.timeLeft - val;
});
}
我的 app.component.html:<p>{{this.DataService.timeLeft}}</p>
我的错误:
无。
杂项。控制台输出:
console.log 打印一次 Juup,然后打印出 timeLeft 的 undefined。每次点击都会发生这种情况。
【问题讨论】:
标签: angular typescript timer rxjs clearinterval