如何在角度6中赋予会话空闲超时?

vik*_*iki 6 session angular angular6

我们正在根据用户角色维护会话。我们想在会话空闲5分钟时实现超时功能。我们正在使用@ ng-idle / core npm模块来做到这一点。

我的服务文件:

 import { ActivatedRouteSnapshot } from '@angular/router';
 import { RouterStateSnapshot } from '@angular/router';
 import {Idle, DEFAULT_INTERRUPTSOURCES, EventTargetInterruptSource} from 
 '@ng-idle/core';
 @Injectable()
export class LoginActService implements CanActivate {
constructor(private authService: APILogService, private router: 
 Router,private idle: Idle) {
  idle.setIdle(10);
  idle.setTimeout(10);
 }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
 ): Observable<boolean>|Promise<boolean>|boolean {
let role = localStorage.getItem('currentUser');

if (localStorage.getItem('currentUser')) {
  if(next.data[0] == role){
   },600000) 
    return true;
  } 
}
else{
  this.router.navigate(['/'], { queryParams: { returnUrl: state.url }});
  return false;
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

作为示例,我使用了setIdle超时5秒钟,但这没有发生。有人可以指导我该怎么做吗?

Nit*_*jan 10

您可以使用bn-ng-idle npm在角度应用程序中检测用户空闲/会话超时。

npm install bn-ng-idle
Run Code Online (Sandbox Code Playgroud)

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { BnNgIdleService } from 'bn-ng-idle'; // import bn-ng-idle service


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [BnNgIdleService], // add it to the providers of your module
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component } from '@angular/core';
import { BnNgIdleService } from 'bn-ng-idle'; // import it to your component

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private bnIdle: BnNgIdleService) { // initiate it in your component constructor
    this.bnIdle.startWatching(300).subscribe((res) => {
      if(res) {
          console.log("session expired");
      }
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我startWatching(timeOutSeconds)300秒(5分钟)调用了该方法,并订阅了可观察对象,一旦用户空闲了5分钟,则将使用res参数的值(这是一个布尔值)调用subscribe方法,如下所示:真正。

通过检查res是否正确,可以显示会话超时对话框或消息。为简便起见,我只是将消息记录到控制台。

  • 什么时候“res”的值为假?当调用进入 subscribe 函数时, res 始终为 true。何时调用 resetTimer 和 stopTimer 方法?我试图显示第一个警告,然后最终会话到期,如上所示,您能帮忙吗,因为没有得到足够的相同实现 (2认同)

小智 8

您可以在主组件或父组件上使用以下代码。假设这是在 admin 父组件中,并且假设您有一个身份验证服务,以便您可以知道用户是否已登录

声明变量

   userActivity;
   userInactive: Subject<any> = new Subject();
Run Code Online (Sandbox Code Playgroud)

在构造函数或 ngOnInit 上添加

   userActivity;
   userInactive: Subject<any> = new Subject();
Run Code Online (Sandbox Code Playgroud)

最后添加以下方法

this.setTimeout();
 this.userInactive.subscribe(() => {
   this.logout();
 });  
 logout() {
 this.authService.logout();
 this.authService.redirectLogoutUser();
}
Run Code Online (Sandbox Code Playgroud)

  • 这假设人们使用鼠标,但情况并非总是如此(触摸屏设备、屏幕阅读器、键盘等) (3认同)

Pra*_*era 5

选项:1: angular-user-idle

逻辑

  • 磁带库正在等待用户1分钟(60秒)的不活动时间。

  • 如果检测到无效,则将onTimerStart()其触发并
    返回倒计时2分钟(120秒)。

  • 如果用户未通过stopTimer()停止计时器,则2分钟(120秒)后时间到,并且onTimeout()被触发。

在AppModule中:

@NgModule({
      imports: [
        BrowserModule,

        // Optionally you can set time for `idle`, `timeout` and `ping` in seconds.
        // Default values: `idle` is 600 (10 minutes), `timeout` is 300 (5 minutes) 
        // and `ping` is 120 (2 minutes).
        UserIdleModule.forRoot({idle: 600, timeout: 300, ping: 120})
      ],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })

In any of your core componets:

    ngOnInit() {
        //Start watching for user inactivity.
        this.userIdle.startWatching();

        // Start watching when user idle is starting.
        this.userIdle.onTimerStart().subscribe(count => console.log(count));

        // Start watch when time is up.
        this.userIdle.onTimeout().subscribe(() => console.log('Time is up!'));
      }
Run Code Online (Sandbox Code Playgroud)

奖励: 您可以使用“ ping”发出请求,以在给定的时间间隔内(例如,每10分钟)刷新令牌。

选项:2:使用ngrx

请参阅链接中的文章:https : //itnext.io/inactivity-auto-logout-w-angular-and-ngrx-3bcb2fd7983f