【发布时间】:2018-08-23 06:33:56
【问题描述】:
在我的 Angular 项目中,我需要在令牌过期之前通过用户交互来刷新它。在 UI 上,我们会在会话过期前 5 分钟显示会话超时消息和更新图标,当用户单击更新图标时,我们会刷新令牌,现在它会再次使用这个新令牌检查会话,依此类推。
RxJs v 5.1
Angular v 4.0
我使用的是setInterval() 和clearInterval(),这里是相关代码
@Compononet({})
export class AdminLayoutComponent implements OnInit {
isRefreshingToken: boolean;
interval: any;
period: number;
constructor() {
this.notifyMinutes = 5; // in minutes
this.isRefreshingToken = false;
this.period = 60 * 1000;
this.timer$ = Observable.timer(0, this.period);
}
ngOninit() {
this.interval = <any>setInterval(() => this.checkSession(), this.period);
}
private checkSession() {
// calculate the remaining time and display the message accordingly
if (remainingTime < 5 minutes) {
this.refreshTokenMethod.finally(() => {
this.isRefreshingToken = false;
}).subscribe() {
this.isRefreshingToken = true;
}
}
}
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
}
这很好,但我认为 Observables 是实现相同目标的更好工具。所以尝试了这种方式
export class AdminLayoutComponent implements OnInit {
timer$: Observable<any>;
subscription: Subscription;
constructor() {
this.timer$ = Observable.timer(0, this.period);
}
ngOnInit() {
this.subscription = this.timer$.subscribe((i) => {
console.log('timer: ', i);
this.checkSession();
});
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
现在的问题是当用户点击更新图标时;我想再次重置计时器以检查时间。
我该怎么做?或者可以运行计时器吗?
【问题讨论】:
标签: angular observable rxjs5