Угловой 6 нг-холостой - PullRequest
       38

Угловой 6 нг-холостой

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

У меня есть Angular Project, который работает хорошо, и я реализую NG-IDLE и KeepAlive, чтобы сохранить сеанс свежим и выйти из системы до истечения сеанса API.

Моя проблемачто ng-idle также работает на странице входа в систему, что, очевидно, не является обязательным, так как по истечении времени ожидания пользователь переходит на страницу входа в систему.

Итак, у меня есть ng-idle иKeepAlive и работает в моем app.component.ts, но так как я использую отложенную загрузку, у меня также есть authentic.module.ts и login.component.ts.

Код в моем корневом приложении.component.ts выглядит следующим образом:

import { Component } from '@angular/core';

import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';

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

export class AppComponent {

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

    constructor(private idle: Idle, private keepalive: Keepalive) {

        // sets an idle timeout of 5 seconds, for testing purposes.
        idle.setIdle(5);

        // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.
        idle.setTimeout(5);

        // 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;
        });

        idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');
        idle.onTimeoutWarning.subscribe((countdown) => this.idleState = 'You will time out in ' + countdown + ' seconds!');

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

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

        this.reset();
    }

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

Я знаю, что мне нужно вызывать idle.unwatch, чтобы предотвратить запуск вхолостую и idle.watch, когда мне это нужно, но как я могу вызвать их измодуль входа в систему или аутентификации, или я могу обнаружить из корневого каталога app.component.ts?

Поскольку вы, несомненно, можете сказать, что я новичок в Angular, прошу прощения, если это вопрос новичка.

Ответы [ 2 ]

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

Так как у кошки всегда есть несколько способов, вот мое собственное решение этой проблемы.Я надеюсь, что кто-то еще найдет это полезным в будущем.

import { Component } from '@angular/core';

import { Location } from '@angular/common';
import { Router } from '@angular/router';

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

export class AppComponent {

    currentPath: String;

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

    constructor(private idle: Idle, private keepalive: Keepalive, location: Location, router: Router) {

        // sets an idle timeout of 5 seconds, for testing purposes.
        idle.setIdle(5);

        // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.
        idle.setTimeout(5);

        // 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;
        });

        idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');
        idle.onTimeoutWarning.subscribe((countdown) => this.idleState = 'You will time out in ' + countdown + ' seconds!');

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

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

        // Lets check the path everytime the route changes, stop or start the idle check as appropriate.
        router.events.subscribe((val) => {

            this.currentPath = location.path();
            if(this.currentPath.search(/authentication\/login/gi) == -1)
                idle.watch();
            else
                idle.stop();

        });
    }

    reset() {
        this.idle.watch();
        this.idleState = 'Started.';
        this.timedOut = false;
    }
}
0 голосов
/ 31 декабря 2018

Одним из способов является создание дома для маршрутов, отличных от входа в систему.Всю логику просмотра и отмены просмотра можно перенести сюда из app.component.ts

In app.routing.ts

const routes: Routes = [
    { path: 'login', component: LoginComponent },
    {
        path: '', component: HomeComponent,
        children: [
            // add auth requiring routes here
        ]
    }
];

In home.component.ts

export class HomeComponent implements OnDestroy {
    constructor() {
        // start watching here
    }  

    ngOnDestroy() {
        // unwatch here
    }
}

In home.component.html

<router-outlet></router-outlet>
...