Automatically forwarding to another page in Angular 4 due to idle time

Is it possible to implement a timeout feature for inactivity on a webpage? For example, if a user is idle for 20 seconds without interacting with the page, can we automatically redirect them to the home screen?

I've been struggling to get this functionality to work with the current code. Any suggestions on how to make it functional?

ngOnInit() {
// Initialize route handling here.

setTimeout((router: Router) => {
    this.router.navigate(['nextRoute']);
}, 20000);  // Timeout set to 20 seconds

}

Answer №1

In order to implement a countdown timer that resets upon user action, you can utilize a host listener to track user interactions:

 @HostListener('document:keyup', ['$event'])
 @HostListener('document:click', ['$event'])
 @HostListener('document:wheel', ['$event'])
 resetTimer () {
    // User action detected
  }

The countdown timer functionality could be structured as follows:

  endCount = new Subject();

// Define end time in minutes   
private initTimer (endTime: number) {
        const interval = 1000;
        const duration = endTime * 60;

        this.subscription = Observable.timer(0, interval)
          .take(duration)
          .subscribe(value => this.render((duration - +value) * interval),
            err => { },
            () => {
              this.endCount.next();
            });
      }

      private render (count) {
        this.secondsDisplay = this.getSeconds(count);
        this.minutesDisplay = this.getMinutes(count);
      }

      private getSeconds (ticks: number) {
        const seconds = ((ticks % 60000) / 1000).toFixed(0);
        return this.pad(seconds);
      }

      private getMinutes (ticks: number) {
        const minutes = Math.floor(ticks / 60000);
        return this.pad(minutes);
      }

      private pad (digit: any) {
        return digit <= 9 ? '0' + digit : digit;
      }

Listen for the endCount event to determine when the user has been inactive for a specific period.

To reset the timer:

resetTimer (newEndTime) {
    this.clearTimer();
    this.initTimer(newEndTime);
  }

   clearTimer () {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
   }

Here is an example implementation on Stackblitz: https://stackblitz.com/edit/angular-2rv3or

Answer №2

If you're looking to avoid creating your own solutions, consider using the NPM module angular-user-idle. It could be a helpful tool for your project.

Here's how you can integrate it into your code:

ngOnInit() {
  //Start monitoring user inactivity.
  this.userIdle.startWatching();

  // Redirect user when idle time is reached.
  this.userIdle.onTimeout().subscribe(() => {
    this.router.navigate(['nextRoute']);
  });
}

Check out the official demo for more information.

Answer №3

To begin, you can install the Idlejs node module by executing the following command:

npm install --save idlejs

After installing the module, import it and add it to your app.component.ts file like this:

import { Idle } from 'idlejs/dist';

const idle = new Idle()
  .whenNotInteractive()
  .within(60)
  .do(() => console.log('IDLE'))
  .start();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding strings in Typescript

I have the following code snippet: let whereClause = 'CurLocation =' + GS + ' and Datediff(DD,LastKYCVerified,GetDate()) >= 180 and CreditCard = ' + 'ACTIVE ' + &ap ...

What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language. One interesting data type I played with is enums. Here's an example of code I used: enum colors {red=1,green=0,blue,white}; console.lo ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

"Using TSOA with TypeScript to return an empty array in the response displayed in Postman

I have successfully implemented CRUD operations using TSOA in TypeScript. However, I am facing an issue where I receive an empty array when making HTTP requests, despite adding data to the 'Livraison' table in MongoDB. https://i.sstatic.net/7IWT ...

Angular: Streamlining the Constructor Function for Efficiency

Consider the scenario where we have these two components: export class HeroComponent { constructor( public service1: Service1, public service2: Service2, ) { // perform some action } } export class AdvancedHeroComponent extends HeroCompone ...

Array of objects not being shown in select dropdown

I have a component with a dropdown feature. Below is the code snippet from the component: export class MyComponent { MyObjectArray: MyObject[] = []; constructor(private _service: MyService) } ngOnInit() { this._service.get().do((response): MyObjec ...

What is the best way to change a string into JSON format within Angular?

Embarking on processing the string below: const json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44 ...

Tips for troubleshooting JavaScript in an Angular 5 application using Visual Studio 2017

I recently developed an Angular 5 web application using VS2017. Initially, the app was functioning well until I decided to enable javascript debugging. Post that change, upon launching the app, I encountered the following error: How can I troubleshoot an ...

The challenges of dealing with duplicate identifiers caused by nesting npm packages in TypeScript

I am facing an issue with my project structure where I have a node_modules folder at the root level and another one within a subfolder named functions. The directory layout looks like this, ├── functions │   ├── index.js │   ├── ...

Using Typescript with React functional components: the proper way to invoke a child method from a parent function

My current setup is quite simple: <Page> <Modal> <Form /> </Modal> </Page> All components mentioned are functional components. Within <Modal />, there is a close function defined like this: const close = () => ...

IntelliSense in VSCode is unable to recognize the `exports` property within the package.json file

Currently, I am utilizing a library named sinuous, which contains a submodule known as "sinuous/map". Interestingly, VSCode seems to lack knowledge about the type of 'map' when using import { map } from "sinuous/map", but it recognizes the type ...

The module '@angular/core' is not found in the Visual Studio Code IDE

It seems like a straightforward code. However, I am encountering the error cannot find module '@angular/core'. course.component.ts import {Component} from '@angular/core' @Component({ selector: 'courses' }) export clas ...

What is the best way to retrieve the final entry from a JSON file while using json server with Angular?

I'm currently working with a JSON file where I am making post requests followed by get requests. My goal is to retrieve the latest record in each get request after submitting a post request. For example: [ { "id": 1, "title&qu ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

Getting Angular 2 and Ionic 2 to play nice together: is it worth the effort?

Recently, I attempted to create a glossary app using Ionic 2 and encountered numerous challenges when incorporating the http service. The Angular 2 tutorials had been updated, configuring the mock server proved difficult, and the Ionic 2 documentation offe ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

Guide to retrieving specific information from a JSON file in an Angular application

Struggling with handling this JSON file [ [ { "category": "Bags", "productData": [ { "id": 1000, "name": "Tro ...

Issues with displaying data in Angular Material table

I am having trouble displaying data in a table. The data shows up when I display it in another element, but not in the table. Here is my code: <mat-accordion *ngIf="posts.length > 0"> <mat-expansion-panel *ngFor="let post of p ...

Enrich your TypeScript code by unleashing the power of enum typing in overloading logical

I have a custom enum called PathDirection that represents different directions export enum PathDirection { LEFT="LEFT"; RIGHT="RIGHT"; }; Within my code, I need to toggle between the two directions. For example: let currentDire ...

How can I provide type annotations for search parameters in Next.js 13?

Within my Next.js 13 project, I've implemented a login form structure as outlined below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "n ...