angular - 如何防止 ng2-idle 在每次成功登录时多次实例化

标签 angular ng-idle

我遇到一个问题,我将空闲设置为在 session 到期前一分钟显示弹出窗口。然后 session 超时或用户注销。当用户下次登录时,如果超时,他们会出现 2 个弹出窗口。用户注销并再次登录,现在有 3 个弹出窗口,依此类推。当用户注销时如何销毁当前的 Idle 实例?

我的设置如下:

constructor(private idle: Idle, ...) {}

ngOnInit() {
    this.setIdle();
}

private setIdle() {
    // Client activity timeout. 29 minutes to 'idle', 1 minute beyond that to timeout
    this.ngZone.runOutsideAngular(() => {
        // this.idle.setIdle(29 * 60);
        // this.idle.setTimeout(1 * 60);
        this.idle.setIdle(10);
        this.idle.setTimeout(10);
        this.idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
    });


    this.idle.onTimeout.subscribe(() => {
        this.ngZone.run(() => {
            this.errorDialogRef.close();
            sessionStorage.setItem('sessionExpired', 'true');
            this.displayErrorModal(true);
        });

    });

    this.idle.onIdleStart.subscribe(() => {
        this.ngZone.run(() => {
            this.displayIdleWarning();
        });
    });

    this.ngZone.runOutsideAngular(() => {
        this.idle.watch();
    });
}

在注销过程中,我尝试了 this.idle.stop()delete this.idle。但两者都不起作用。

仅供引用:它必须运行在 Angular 区域之外,否则我们的 Protractor 测试就会中断。

更新: 在找到将数组归零的解决方案之前,我确实尝试过:

this.idle.onTimeout.unsubscribe();
this.idle.onIdleStart.unsubscribe();
this.idle.onIdleEnd.unsubscribe();

但这只会导致后续登录时出现以下错误:

core.es5.js?0445:1084 ERROR Error: Uncaught (in promise): ObjectUnsubscribedError: object unsubscribed 

在我看来,我的组件保留了其引用,或者在注销期间没有被破坏。

最佳答案

我能够检查 this.idle 对象并发现“do stuff”对象(onTimeoutonIdleStartonIdleEndonInterruptonTimeoutWarning)是 EventEmitters。其中每一个都有一个名为“观察者”的对象。 observers 是一个观察者数组。每次创建新的弹出窗口时,我注意到数组都增加了。因此,在注销过程中,我只是清除了观察者:

this.idle.stop();
this.idle.onTimeout.observers.length = 0;
this.idle.onIdleStart.observers.length = 0;
this.idle.onIdleEnd.observers.length = 0;

这可能不是最好的方法。我确信有更好的方法从 EventEmitter 中删除观察者。但我找不到它,这是一种快速而肮脏的方法。

关于angular - 如何防止 ng2-idle 在每次成功登录时多次实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45363467/

相关文章:

AngularJS:未知提供者:$idleProvider

angular - ng-idle/core onIdleEnd 和 Mat-Dialog 有问题

javascript - 错误 : "Can' t create a Google Chart without data!“当数据加载到异步 Angular 服务中时

angular - 如何在 Angular 6 中导入 sass 文件

javascript - Angular 2 : How to hide button only on selective iteration of *ngFor?

javascript - 单击图标打开文件资源管理器

node.js - Electron - 构建应用程序时找不到模块 'app'

javascript - ng-idle 无法读取属性