Исключить компонент входа в систему из функции тайм-аута сессии в app.component.ts - PullRequest
0 голосов
/ 06 декабря 2018

В моем приложении должно быть всплывающее окно сессионного тайм-аута, если пользователь не используется в течение 20 минут.Я поместил этот код в app.component.ts, чтобы всплывающее окно отображалось на каждой странице, но моя проблема в том, что я не хочу, чтобы этот код применялся к моей странице входа.Как я могу исключить эту часть из показа на моей странице входа в систему?

Я уже думал о создании службы времени ожидания сеанса для внедрения в каждый другой компонент, но у меня слишком много компонентов / страниц, поэтому я подумалбыло бы проще поместить его в основной app.component.ts и найти способ исключить LoginComponent.Любая помощь будет принята с благодарностью:)

Изображение того, чего я не хочу - страница входа

Что я хочу - на каждой другой странице

Ниже мой app.component.ts

 import {Component, OnInit,ElementRef } from '@angular/core';
 import {NgxSpinnerService } from 'ngx-spinner';
 import {ProgressBarModalComponent} from './progressbar-modal.component';
 import {Router} from '@angular/router'
 import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
 import {NgbModalRef} from '@ng-bootstrap/ng-bootstrap/modal/modal.module';
 import {Idle } from "@ng-idle/core";
 import {Keepalive} from '@ng-idle/keepalive';
 import {LoginComponent } from './login/login.component';
 import {OnDestroy } from '@angular/core';
 import {interval, Subscription } from 'rxjs';
 import {startWith, switchMap } from 'rxjs/operators';
 import {EventTargetInterruptSource} from '@ng-idle/core';
 import {CookieService } from 'ngx-cookie-service';

 @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css']
 })
 export class AppComponent implements OnInit{
  title = 'TxDOTCONNECT';
  idleState = 'NOT_STARTED';
  timedOut = false;
  lastPing?: Date = null;
  progressBarPopup: NgbModalRef;

  constructor(
    private element: ElementRef, 
    private idle: Idle, 
    private keepalive: Keepalive, 
    private router:Router,
    private ngbModal: NgbModal, 
    private cookieService:CookieService) {

idle.setIdle(1155);     //    sets an idle timeout of 19 minutes 50 seconds.

idle.setTimeout(10);   //     sets a timeout period of 10 seconds.

idle.setInterrupts([    //     sets the interrupts like Keydown, scroll, mouse wheel, mouse down, and etc
  new EventTargetInterruptSource(
    this.element.nativeElement, 'keydown DOMMouseScroll mousewheel mousedown touchstart touchmove scroll')]);

idle.onIdleEnd.subscribe(() => {
  this.idleState = 'NO_LONGER_IDLE';
});

idle.onTimeout.subscribe(() => {
  this.idleState = 'TIMED_OUT';
  this.timedOut = true;
  this.logout();
  this.closeProgressForm();
});

idle.onIdleStart.subscribe(() => {
  this.idleState = 'IDLE_START', this.openProgressForm(1);
});

idle.onTimeoutWarning.subscribe((countdown: any) => {
  this.idleState = 'IDLE_TIME_IN_PROGRESS';
  this.progressBarPopup.componentInstance.count = (Math.floor((countdown - 1) / 10) + 1);
  this.progressBarPopup.componentInstance.progressCount = this.reverseNumber(countdown);
  this.progressBarPopup.componentInstance.countMinutes = (Math.floor(countdown / 60));
  this.progressBarPopup.componentInstance.countSeconds = countdown%60;
});

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

/**
 *  // Keepalive can ping request to an HTTP location to keep server session alive
 * keepalive.request('<String URL>' or HTTP Request);
 * // Keepalive ping response can be read using below option
 * keepalive.onPing.subscribe(response => {
 * // Redirect user to logout screen stating session is timeout out if if response.status != 200
 * });
 */

this.reset();
} 

reverseNumber(countdown: number) {
    return (300 - (countdown - 1));
  }

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

  openProgressForm(count: number) {
    this.progressBarPopup = this.ngbModal.open(ProgressBarModalComponent, {
      backdrop: 'static',
      keyboard: false
    });
    this.progressBarPopup.componentInstance.count = count;
    this.progressBarPopup.result.then((result: any) => {
      if (result !== '' && 'logout' === result) {
        this.logout();
      } else {
        this.reset();
      }
    });
    console.log('opening session timeout pop up')
  }

  logout() {
    this.router.navigate([' environment.loginPage'])
    console.log('Logging user out due to inactivity')
    sessionStorage.clear();
    this.cookieService.deleteAll();
    console.log('Deleting all cookies made during the session')
  }

  closeProgressForm() {
    this.progressBarPopup.close();
  }

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

    ngOnDestroy(): void {
      this.resetTimeOut();
  }

  ngOnInit() {

  }

}

1 Ответ

0 голосов
/ 07 декабря 2018

Просто разобрался, если кто-то хочет знать.В моем NgOnInit () я добавил этот код.

  this.router.events
  .filter((event) => event instanceof ActivationEnd)
  .subscribe((event) => {
    if (this.router.url.indexOf(environment.loginPage) === -1) {
       //session-timeout logic here
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...