根据用户操作重置 Observable Timer?

Reset the Observable Timer on user action?

在我的 angular 项目中,我需要通过用户交互在令牌过期之前刷新它。在 UI 上,我们在会话到期前 5 分钟显示会话超时消息和更新图标,当用户单击更新图标时,我们刷新令牌,现在它再次使用这个新令牌检查会话,依此类推。

我正在使用 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();
        }
    }
}

现在的问题是,当用户点击更新图标时;我想重新设置定时器以检查时间。

我该怎么做?或者 运行 计时器可以吗?

您需要使用 Subject Observable。使用 next() 重置计时器。

export class AdminLayoutComponent implements OnInit {

    private reset$ = new Subject();
    timer$: Observable<any>;
    subscription: Subscription;

    constructor() {
        this.timer$ = this.reset$.pipe(
          startWith(0),
          switchMap(() => timer(0, 30000))
        );
    }

    ngOnInit() {
        this.subscription = this.timer$.subscribe((i) => {
            console.log('timer: ', i);
            this.checkSession();
        });
    }

   refreshTimer(): void {
      this.reset$.next(void 0);
    }

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}

还更新了 stackblitz 代码 https://stackblitz.com/edit/angular-pnwh44