Angular 2 - Logout using ng2-idle

馋奶兔 提交于 2019-12-06 09:13:54

问题


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

回答1:


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();



来源:https://stackoverflow.com/questions/39192832/angular-2-logout-using-ng2-idle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!