Home > Software design >  how to logout user if user is inactive for particular time in angular?
how to logout user if user is inactive for particular time in angular?

Time:03-24

I am working in angular. I want to log out the user if he is inactive. I found the solution but that was only for a particular page. I have a lot of pages so I can't put the same code in each code. Is there any way to catch inactivity globally in angular?

I tried this code and it works but it works only for a particular page.

constructor() { 
    this.setTimeout();
    this.userInactive.subscribe(() => console.log('user has been inactive for 3s'));
  }

  userActivity:any;
  userInactive: Subject<any> = new Subject();
  
  setTimeout() {
    this.userActivity = setTimeout(() => this.userInactive.next(undefined), 3000);
  }

  @HostListener('window:mousemove') refreshUserState() {
    clearTimeout(this.userActivity);
    this.setTimeout();
  }

CodePudding user response:

Hi for this issue I thing you have to implement it module level or through out the application. for example in AppComponent you can put this logic and check if user is Logged In.

And He is Inactive for desired time 1 minute or 2 Minute You can call the logout service and redirect user again to Login Page.

Also there are some npm library available to check idle below is one library

npm library : angular-user-idle

demo : Demo

  • Related