python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
angular 2 auto logout using ng2-idle

Angular 2 - Auto Logout using ng2-idle

Why use Auto Logout in Angular 1 or Angular 2?
1.     A user must be logged out after 10 to 15 minutes (As per you).
2.     Every click interaction must reset the timer.
3.     The timer must be synchronized between tabs and so on.
4.     If users close the tab before your timer expires, he gets logged out when he visits again.

Stayed Informed - Angular 1 auto logout!

The below example helps us to handling the “Auto Logout” mechanism to maintain to web applications using “ng2-idle”.

import {Component } from '@angular/core';
import {Idle, DEFAULT_INTERRUPTSOURCES } from 'ng2-idle/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';

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

export class AppHeaderComponent {
    nome :any = localStorage['app-appHeader'];

    constructor(private router: Router,
        private http: Http,
        private headerService: HeaderService,
        private idle: Idle) {

        idle.setIdle(10);
        idle.setTimeout(3600);
        idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

        idle.onTimeoutWarning.subscribe((countdown: number) => {
            alert('Timeout Warning - ' + countdown);
        });

        idle.onTimeout.subscribe(() => {
          alert('Timeout');
          localStorage.clear();

          this.router.navigate(['/auth', {sessionExpirate: 'true'}]);
        });

        idle.watch();
    }

    logout() {
        this.idle.stop();
        this.idle.ngOnDestroy(); //includes this.idle.stop() and this.clearInterrupts() both.
        this.headerService.exit()
            .subscribe(
                data => {
                    localStorage.clear();
                    this.router.navigate(['/auth']);
                },
                error => console.log(error)
            )
    }  
}

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions