Angular ng2-idle在多个页面上订阅

时间:2017-09-04 06:56:12

标签: angular ng2-idle

import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';

export class Calender {

    idleState = 'Not started.';
    timedOut = false;
    lastPing?: Date = null;

    constructor(private idle: Idle, private keepalive: Keepalive) {


        idle.setIdle(30);

        idle.setTimeout(30);

        idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);


        idle.onIdleEnd.subscribe(() => this.idleState = 'No longer idle.');

        idle.onTimeout.subscribe(() => {

          this.timedOut = true;
       });

        idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');
        idle.onTimeoutWarning.subscribe((countdown) => this.idleState = 'You will time out in ' + countdown + ' seconds!');

        keepalive.interval(15);

        this.reset();
    }
    reset() {
        this.idle.watch();
        this.idleState = 'Started.';
        this.timedOut = false;
    }

从上面的代码中我使用ng2-idle关于如何在空闲会话上实现超时,但是从代码中它只是在一个页面上实现,但现在我的角度2中有超过5页项目,我需要在每个页面中放置此代码以订阅超时并启动计数器?如果时间到期,它会在其他页面上启动计数器,它会影响所有

1 个答案:

答案 0 :(得分:0)

以下是角度空闲会话过期超时警告的示例

import { Component } from '@angular/core';
import { EventTargetInterruptSource, Idle } from '@ng-idle/core';
import { ElementRef } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    idleState = 'NOT_STARTED';
    timedOut = false;
    lastPing?: Date = null;
    constructor(private element: ElementRef, private idle: Idle) {
        // sets an idle timeout of 15 minutes.
        idle.setIdle(900);
        // sets a timeout period of 5 minutes.
        idle.setTimeout(300);
        // sets the interrupts like Keydown, scroll, mouse wheel, mouse down, and etc
        const x = 'keydown DOMMouseScroll mousewheel mousedown touchstart touchmove scroll';
        idle.setInterrupts([new EventTargetInterruptSource(this.element.nativeElement, x)]);
        idle.onIdleEnd.subscribe(() => {
            this.idleState = 'NO_LONGER_IDLE';
        });
        idle.onTimeout.subscribe(() => {
            this.idleState = 'TIMED_OUT';
            this.timedOut = true;
            console.log('onTimeout');
        });
        idle.onIdleStart.subscribe(() => {
            this.idleState = 'IDLE_START';
            console.log('idleStart');
        });

        idle.onTimeoutWarning.subscribe((countdown: any) => {
            this.idleState = 'IDLE_TIME_IN_PROGRESS';
        });

        this.idle.watch();
        this.idleState = 'Started.';
        this.timedOut = false;
    }

    logOut() {
        this.idle.stop();
        this.idle.onIdleStart.unsubscribe();
        this.idle.onTimeoutWarning.unsubscribe();
        this.idle.onIdleEnd.unsubscribe();
        this.idle.onIdleEnd.unsubscribe();
    }
}

基于此来源https://github.com/programmingwithnaveen/Session-Timeout