angularlogoutng-idle

Angular 2 - Logout using ng2-idle


My problem is that when click on the logout button ng2-idle continues working. And to try to solve this problem I set again the setIdle and setTimeout functions for 1 second.

However, when the user is transferred to the login screen, the app takes 1 second to give the timeout.

I like to know if have any way of forcing the timeout or end ng2-idle after click the logout button that call logout() function.

import {Component} from '@angular/core';
import {Router} from "@angular/router";
import {Http, Headers} from "@angular/http";
import {NgClass} from '@angular/common';
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';
import {HeaderService} from './header.service';
import {Idle, DEFAULT_INTERRUPTSOURCES} from 'ng2-idle/core';

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

export class HeaderComponent {
    nome = localStorage['nome'];
    constructor(private _router: Router, private _http: Http, private _headerService: HeaderService, private idle: Idle) {
        idle.setIdle(5);
        idle.setTimeout(1800);
        idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

        idle.onTimeoutWarning.subscribe((countdown:number) => {
          console.log('TimeoutWarning: ' + countdown);
        });

        idle.onTimeout.subscribe(() => {
          console.log('Timeout');
          localStorage.clear();
          this._router.navigate(['/auth', {sessionExpirate: 'true'}]);
        });
        idle.watch();
    }

    logout() {
        this.idle.setIdle(1);
        this.idle.setTimeout(1);
        this.idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
        this._headerService.exit()
            .subscribe(
                data => {
                    this.idle.onTimeout.subscribe(() => {
                        console.log('Timeout');
                        localStorage.clear();
                        this._router.navigate(['/auth']);
                },
                error => console.log(error)
            )}
        )
    }  
}

Solution

  • I got to work, follows the change in the logout() function:

    logout() {
        this.idle.stop();
        this._headerService.exit()
            .subscribe(
                data => {
                    localStorage.clear();
                    this._router.navigate(['/auth']);         
                },
                    error => console.log(error)
            )                          
        }
    

    It is possible to use both function this.idle.stop() or this.idle.ngOnDestroy(); idle.ts

    The this.idle.ngOnDestroy(); includes this.idle.stop() and this.clearInterrupts();