Issue
We are maintaining a session based on user role. We want to implement timeout functionality when the session is idle for 5 min. We are using @ng-idle/core npm module to do that.
My Service file:
import { ActivatedRouteSnapshot } from '@angular/router';
import { RouterStateSnapshot } from '@angular/router';
import {Idle, DEFAULT_INTERRUPTSOURCES, EventTargetInterruptSource} from
'@ng-idle/core';
@Injectable()
export class LoginActService implements CanActivate {
constructor(private authService: APILogService, private router:
Router,private idle: Idle) {
idle.setIdle(10);
idle.setTimeout(10);
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
let role = localStorage.getItem('currentUser');
if (localStorage.getItem('currentUser')) {
if(next.data[0] == role){
},600000)
return true;
}
}
else{
this.router.navigate(['/'], { queryParams: { returnUrl: state.url }});
return false;
}
}
}
For sample, I have used setIdle timeout for 5 seconds, But it is not happening. Can somebody guide me how to do this?
Solution
You can use bn-ng-idle npm for user idle / session timeout detection in angular apps. This blog post explanation will help you Learn how to Handle user idleness and session timeout in Angular
npm install bn-ng-idle
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BnNgIdleService } from 'bn-ng-idle'; // import bn-ng-idle service
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [BnNgIdleService], // add it to the providers of your module
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { BnNgIdleService } from 'bn-ng-idle'; // import it to your component
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private bnIdle: BnNgIdleService) { // initiate it in your component constructor
this.bnIdle.startWatching(300).subscribe((res) => {
if(res) {
console.log("session expired");
}
})
}
}
In the above example, I have invoked the startWatching(timeOutSeconds)
method with 300 seconds (5 minutes) and subscribed to the observable, once the user is idle for five minute then the subscribe method will get invoked with the res parameter's value (which is a boolean) as true.
By checking whether the res is true or not, you can show your session timeout dialog or message. For brevity, I just logged the message to the console.
Answered By - Nithya Rajan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.