使用 ng-idle 的 Angular 4 会话超时 [英] Session Timeout in angular 4 using ng-idle

查看:120
本文介绍了使用 ng-idle 的 Angular 4 会话超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我引用了 https://hackedbychinese.github.io/ng2-idle/ 并将其修改为 ,在 onTimeoutWarning 期间将打开一个模态弹出窗口,超时会话将被清除并导航到登录页面.

它工作正常.但是,导航到登录页面后,如果用户再次登录,则超时功能不起作用.

组件

import { Component, ViewChild } from '@angular/core';导入 'rxjs/add/operator/map';从 '../Service/session.service' 导入 { SessionService };从'../Service/login.service'导入{登录服务};从@angular/router"导入{路由器};从'@angular/common'导入{DatePipe};从'@ng-idle/core'导入{空闲,DEFAULT_INTERRUPTSOURCES};从'@ng-idle/keepalive'导入{Keepalive};从 'ng2-bs3-modal/ng2-bs3-modal' 导入 { ModalComponent };从'rxjs'导入{主题};@成分({选择器:'应用程序头',templateUrl: 'app/HTML/header.html'})导出类 HeaderComponent {//今天日期:字符串;公共员工详细信息:字符串 =";IsLoggedOut: boolean = true;idleState = '未开始.';超时=假;lastPing?:日期=空;公共标志:boolean = false;public sessionWarningTimer$ = new Subject();今天日期:字符串;公共当前日期:日期 = 新日期();@ViewChild('modal') modal: ModalComponent;构造函数(私人_loginservice:登录服务,私有_sessionService:会话服务,专用路由器:路由器,公共日期管道:DatePipe,私人空闲:空闲,私人保活:保活,){_loginservice.getLoggedInName.subscribe(name => this.changeName(name));if (_sessionService.getItem("CurrentUser") != null) {this.TodayDate = this.datePipe.transform(Date.now(), 'MM/dd/yyyy');_loginservice.set(this._sessionService.getItem("CurrentUser").LastName + " " + this._sessionService.getItem("CurrentUser").FirstName + " | " + "Emp No - " + this._sessionService.getItem("CurrentUser").EmployeeNumber + " | " + "Dept - " + this._sessionService.getItem("CurrentUser").CurrentEmployee.DepartmentId + " | " + this._sessionService.getItem("CurrentUser").CurrentEmployee.FullTime + "| " + this._sessionService.getItem("CurrentUser").CurrentEmployee.Exempt );}/*********************************************************************************************************/this.reset();//将空闲超时设置为 5 秒,用于测试目的.idle.setIdle(50);//设置超时时间为 5 秒.10 秒不活动后,用户将被视为超时.idle.setTimeout(50);//设置默认中断,在这种情况下,例如单击、滚动、触摸文档idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);idle.onIdleEnd.subscribe(() => this.idleState = '不再空闲.');idle.onTimeout.subscribe(() => {this.idleState = '超时!';this.timedOut = true;//登出this._loginservice.set("");this._sessionService.setItem("IsLoggedOut", true);this._sessionService.removeItem("CurrentUser");this.flag = false;this.timedOut = false;this.idleState = '';this.router.navigate(['登录']);this.modal.dismiss();});idle.onIdleStart.subscribe(() => this.idleState = '你已经闲置了!');idle.onTimeoutWarning.subscribe((倒计时) => {this.idleState = '您的会话即将过期,您将在'+倒计时+'秒后退出!';如果(!this.flag){this.modal.open();this.flag = true;}});//设置ping间隔为15秒keepalive.interval(15);keepalive.onPing.subscribe(() => this.lastPing = new Date());this.reset();/*********************************************************************************************************/}私人更改名称(名称:字符串):无效{this.EmployeeDetail = 姓名;}登出() {this._loginservice.set("");this._sessionService.setItem("IsLoggedOut", this.IsLoggedOut);this._sessionService.removeItem("CurrentUser");this.router.navigate(['登录']);}重置() {this.idle.watch();this.idleState = '开始.';this.timedOut = false;}}

HTML

<h3 class="pageTitle">会话超时</modal-header><模态体><部分><p><strong>{{idleState}}</strong></p><!--<p *ngIf="lastPing"><small>最后一次保活 ping <strong>{{lastPing |date:'h:mm a z'}} TimeAgo</strong></small></p><button (click)="reset()" *ngIf="timedOut">继续会话</button>--></节></modal-body><模态页脚><div *ngIf="!timedOut"><a class="btn btn-default" (click)="modal.dismiss()">继续会话</a>

</modal-footer>

解决方案

你应该像这样改变你的onTimeout subscribe.它对我有用.

 this.idle.onTimeout.subscribe(() => {//console.log('超时')this.idleState = '超时!';this.timedOut = true;swal.close();this.idle.stop();//防止多次初始化this.idle.onTimeout.observers.length = 0;this.idle.onIdleStart.observers.length = 0;this.idle.onIdleEnd.observers.length = 0;this.signOut(this.getPath().substring(1));});

I have referred code from https://hackedbychinese.github.io/ng2-idle/ and modified it as , during onTimeoutWarning a modal popup will be opened and on timeout session will be cleared and navigated to Login page.

It is working fine. However, after navigating to Login page if user is logging in again, then timeout functionality is not working.

Component

import { Component, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { SessionService } from '../Service/session.service';
import { LoginService } from '../Service/login.service';
import { Router } from '@angular/router';
import { DatePipe } from '@angular/common';
import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { Subject } from 'rxjs';
@Component({
    selector: 'app-header',
    templateUrl: 'app/HTML/header.html'
})

export class HeaderComponent {


    //TodayDate: string;
    public EmployeeDetail: string = "";
    IsLoggedOut: boolean = true;

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

    public flag: boolean = false;
    public sessionWarningTimer$ = new Subject();
    TodayDate: string;
    public CurrentDate: Date = new Date();
    @ViewChild('modal') modal: ModalComponent;


    constructor(
        private _loginservice: LoginService,
        private _sessionService: SessionService,
        private router: Router,
        public datePipe: DatePipe,
        private idle: Idle,
        private keepalive: Keepalive,) {

        _loginservice.getLoggedInName.subscribe(name => this.changeName(name));

        if (_sessionService.getItem("CurrentUser") != null) {
            this.TodayDate = this.datePipe.transform(Date.now(), 'MM/dd/yyyy');
            _loginservice.set(this._sessionService.getItem("CurrentUser").LastName + " " + this._sessionService.getItem("CurrentUser").FirstName + " | " + "Emp No - " + this._sessionService.getItem("CurrentUser").EmployeeNumber + " | " + "Dept - " + this._sessionService.getItem("CurrentUser").CurrentEmployee.DepartmentId + " | " + this._sessionService.getItem("CurrentUser").CurrentEmployee.FullTime + " | " + this._sessionService.getItem("CurrentUser").CurrentEmployee.Exempt  );

        }

        /**************************************************************************************************/
        this.reset();
        // sets an idle timeout of 5 seconds, for testing purposes.
        idle.setIdle(50);
        // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.
        idle.setTimeout(50);
        // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
        idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

        idle.onIdleEnd.subscribe(() => this.idleState = 'No longer idle.');
        idle.onTimeout.subscribe(() => {
            this.idleState = 'Timed out!';
            this.timedOut = true;
            //Logout

            this._loginservice.set("");
            this._sessionService.setItem("IsLoggedOut", true);
            this._sessionService.removeItem("CurrentUser");
            this.flag = false;
            this.timedOut = false;
            this.idleState = '';
            this.router.navigate(['Login']);
            this.modal.dismiss();
        });
        idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');
        idle.onTimeoutWarning.subscribe((countdown) => {
            this.idleState = 'Your session is about to expire and you will logged out in ' + countdown + ' seconds!';
            if (!this.flag) {
                this.modal.open();
                this.flag = true;
            }
        });

        // sets the ping interval to 15 seconds
        keepalive.interval(15);

        keepalive.onPing.subscribe(() => this.lastPing = new Date());

        this.reset();
        /**************************************************************************************************/
    }
    private changeName(name: string): void {
        this.EmployeeDetail = name;
    }


    Logout() {
        this._loginservice.set("");
        this._sessionService.setItem("IsLoggedOut", this.IsLoggedOut);
        this._sessionService.removeItem("CurrentUser");
        this.router.navigate(['Login']);
    }

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

    }
}

HTML

<modal-header [show-close]="true">
    <h3 class="pageTitle">
        Session Timeout
    </h3>
</modal-header>
<modal-body>

    <section>
        <p><strong>{{idleState}}</strong></p>
        <!--<p *ngIf="lastPing"><small>Last keepalive ping <strong>{{lastPing | date:'h:mm a z'}} TimeAgo</strong></small></p>
        <button (click)="reset()" *ngIf="timedOut">Continue Session</button>-->
    </section>



</modal-body>
<modal-footer>
    <div *ngIf="!timedOut">
        <a class="btn btn-default" (click)="modal.dismiss()">Continue Session</a>
    </div>
</modal-footer>

解决方案

You should change your onTimeout subscribe like this. It worked with me.

 this.idle.onTimeout.subscribe(() => {
          //console.log('timeout')
          this.idleState = 'Timed out!';
          this.timedOut = true;
          swal.close();
          this.idle.stop();
          //prevent init multiple time
          this.idle.onTimeout.observers.length = 0;
          this.idle.onIdleStart.observers.length = 0;
          this.idle.onIdleEnd.observers.length = 0;

          this.signOut(this.getPath().substring(1));
});

这篇关于使用 ng-idle 的 Angular 4 会话超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆