0

I am trying to display an alert message for my application if the user is Idle for some seconds ( 5 sec ). So I installed the bn-ng-Idle package.

It works fine for the click, resize, and keypress events, but it does not work for mouseover events.

Even if I hover the mouse in the application it shows the alert box. And also it does not work for beforeunload event. If I close the window and open it again, it starts the count from 0.

  • I attached the code below:

  • bn-ng-idle.service.ts:

import { Injectable } from '@angular/core';
import { Observable, fromEvent, merge, Subject, timer, Subscription, mergeMap } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class BnNgIdleService {

  private idle$!: Observable<any>;
  private timer$!: Subscription;
  private timeOutMilliSeconds!: number;
  private idleSubscription!: Subscription;

  public expired$: Subject<boolean> = new Subject<boolean>();

  constructor() {

  }

  public startWatching(timeOutSeconds: number): Observable<any> {
    this.idle$ = merge(
      fromEvent(document, 'mousemove'),
      fromEvent(document,'focus'),
      fromEvent(window, 'click'),
      fromEvent(document, 'mousedown'),
      fromEvent(document, 'keypress'),
      fromEvent(document, 'DOMMouseScroll'),
      fromEvent(document, 'mousewheel'),
      fromEvent(document, 'touchmove'),
      fromEvent(document, 'MSPointerMove'),
      fromEvent(window, 'mousemove'),
      fromEvent(window, 'resize'),
    );

    this.timeOutMilliSeconds = timeOutSeconds * 1000;

    this.idleSubscription = this.idle$.subscribe((res) => {
      this.resetTimer();
    });

    this.startTimer();

    return this.expired$;
  }

  private startTimer() {
    this.timer$ = timer(this.timeOutMilliSeconds, this.timeOutMilliSeconds).subscribe((res) => {
      this.expired$.next(true);
    });
  }

  public resetTimer() {
    this.timer$.unsubscribe();
    this.startTimer();
  }

  public stopTimer() {
    this.timer$.unsubscribe();
    this.idleSubscription.unsubscribe();
  }
}

  • app.component.ts :
import { Component, OnInit } from '@angular/core';
import { BnNgIdleService } from './bn-ng-idle.service';
// import { BnNgIdleService } from 'bn-ng-idle';

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

  constructor(private bnIdle : BnNgIdleService){}

  


  ngOnInit(): void {
    this.bnIdle.startWatching(5).subscribe(
      (isTimeOut:boolean)=> {
        if(isTimeOut){
          // console.log("session expired!");
          console.log(isTimeOut);
          
          alert("You are Idle")
          this.bnIdle.resetTimer();
        }
        else{
          console.log("hi");

        }
        
      }
    )
  }



}

Please help to fix this and tell me what I am doing wrong in it.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
vijay s
  • 147
  • 1
  • 4
  • 15

0 Answers0