0

thanks in advance for your response. I am implementing an inactivity log out and it works just fine. Right now I have this implemented in my home component only, but, of course I want to use it in my whole application. I tried in app.component.ts, but the problem is that it it only works once when you load the page and login, it starts watching the whole app, but when it logs you out it doesn't work anymore because app.component onInit only triggers once, unless the page is reloaded. I have no idea how to make this without having to copy this code in every component of my app. Any ideas?

Here's my code:

This component is injected in my home.component.ts


import { Component, OnInit, NgZone, ChangeDetectorRef } from '@angular/core';
import { ProvisionedService } from '../../devices/provisioned-list/provisioned.service';
import { UsersService } from '../../users/users.service';
import { fromEvent, merge, interval, Observable, of, Subscription } from 'rxjs';
import { switchMap, take, skipWhile, takeLast, skipUntil, tap } from 'rxjs/operators';
import { FuseConfirmDialogComponent } from "@fuse/components/confirm-dialog/confirm-dialog.component";
import { MatDialogRef, MatDialog } from "@angular/material";
import { StorageService } from '../../common/services/storage.service';
import { AuthService } from '../../common/services/auth.service';
import { Router } from '@angular/router';



@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  deviceList: DeviceModel[];
  devicesAlive: any;
  vanillaDevices: DeviceModel[];
  getDevicesInfoLoop: any;
  isAlive: any;
  invitationList: InvitationModel[];
  deviceId: any

  inactivityTime: number = 15;

  timeLapsedSinceInactivity: number = 0;
  seconds: number = this.padZero(0);
  subscription: Subscription;
  observeable$: Observable<any>;
  mergedObservable$: Observable<any>;
  event: Event;
  confirmDialogRef: MatDialogRef<FuseConfirmDialogComponent>;

  public inactivityTimerEvent: Array<any>[] = [[document, 'click'], [document, 'wheel'], [document, 'scroll'], [document, 'mousemove'],
   [document, 'keyup'], [window, 'resize'], [window, 'scroll'], [window, 'mousemove']];



  constructor(private provisionedService: ProvisionedService, private VanillaService: VanillaService, 
    private UsersService: UsersService, public _ngZone: NgZone,
    public _cd: ChangeDetectorRef,
    public matDialog: MatDialog,
    public storageService: StorageService,
    private authService: AuthService,
    private router: Router) {
  }

  ngOnInit() {

    let observableArray$: Observable<any>[] = [];

    this.inactivityTimerEvent.forEach(x => {
      observableArray$.push(fromEvent(x[0], x[1]))
    })
    this.mergedObservable$ = merge(...observableArray$);

    this.startTimer(event);


  }

  public createObserable(): void {
    this._ngZone.runOutsideAngular(() => {

      this.observeable$ = this.mergedObservable$
      .pipe(
        switchMap(ev => interval(1000).pipe(take      (this.inactivityTime))),

        tap(value => this.isItTimeToShowPopUp(value)),

        skipWhile((x) => {
          this.timeLapsedSinceInactivity = x;
          return x != this.inactivityTime - 1
        })
      );

      this.subscribeObservable();
    })

  }

  public isItTimeToShowPopUp(val: number) {
    let timeLeftForInactive = this.inactivityTime - val;
    if (timeLeftForInactive <= 15) {

      this.timeLapsedSinceInactivity = timeLeftForInactive;
      this.seconds = this.padZero(timeLeftForInactive % 15);
      this._cd.detectChanges();
      console.log(timeLeftForInactive);
    }



    if(timeLeftForInactive === 1) {
      this.authService.removeUserData();
      this.storageService.removelocalStorageData();
      this.router.navigate(['/login']);

    }
    }



  public subscribeObservable() {
    this.subscription = this.observeable$.subscribe((x) => {
      console.log(`subscribed for ${x + 1} sec`);
      this.unsubscribeObservable()
    })
  }
  public padZero(digit: any) {
    return digit <= 9 ? '0' + digit : digit;
  }

  public unsubscribeObservable() {
    console.log('  unsubscriebd')
    this.subscription.unsubscribe();
  }

  public startTimer($event) {
    this.createObserable();
    console.log('subscription started');
  }
  public stopTimer(event) {
    if (this.subscription && !this.subscription.closed) {
      this.seconds = this.padZero(0);
      this.unsubscribeObservable();
    }
  }


}


novita
  • 139
  • 1
  • 15

2 Answers2

0

You should put your code in app.component.ts Or better make separate service which handles this.

So that it will be available to the whole app.

Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41
0

Yes, you are right. When I implemented session idle timeout feature in my app, this post helped me. [https://stackoverflow.com/a/51651151/12222270]

Here goes my app.component.ts

import { Component, HostListener } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/index';


@Component({
  providers: [],
  selector: 'intellect-app',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html'
})

export class AppComponent {

  private userActivity;
  private userInactive: Subject<any> = new Subject();

  public constructor(
    private router: Router
  ) {

    this.startTimer();

    this.userInactive.subscribe(() => this.router.navigateByUrl('/login'));

  }

  private startTimer() {

    this.userActivity = setTimeout(() => this.userInactive.next(undefined), 5000);

  }

  @HostListener('window:resize')
  @HostListener('window:scroll')
  @HostListener('window:mousemove')
  @HostListener('document:click')
  @HostListener('document:wheel')
  @HostListener('document:scroll')
  @HostListener('document:mousemove')
  @HostListener('document:keyup') resetTimer() {

    clearTimeout(this.userActivity);

    this.startTimer();

  }

}
  • it works when you charge the app the first time and log in the first time. If the timer logs you out and log in again doesn't work as appComponent OnInit won't be triggered unless you reload the page. – novita Jun 03 '20 at 16:47
  • @novita I have edited my answer. Please refer that. Hope that helps! – Karthik Velayudham Jun 03 '20 at 22:12