Angular - Restarting the inactivity redirection feature upon moving to a different page

I've implemented a feature in my Angular app that redirects users to a screensaver page after 30 seconds of inactivity, using code I found here. The functionality works well, but I'm facing an issue where I don't want the redirection to occur on certain pages. Even when navigating away from a redirection-enabled page to one without redirection, the timer continues running. How can I disable it upon each navigation?


Here is a snippet of my code:

timeout;
...
resetTimer(endTime: number = this.endTime) {
  const interval = 1000;
  const duration = endTime * 60;

  this.timerSubscription = timer(0, interval)
    .pipe(take(duration))
    .subscribe(
      value => this.render((duration - +value) * interval),
      err => {},
      () => {
        this.timeout = setTimeout(() => {
          this.navCtrl.navigateRoot(URL_CONSTANT.SCREENSAVER, {
            animated: false
          }, 100);
        });
      }
    );
}
...
ngOnDestroy() {
  this.unsubscribe$.next();
  this.unsubscribe$.complete();
  clearTimeout(this.timeout);
}

Answer №1

To ensure proper cleanup, it's important to keep a reference to the timeout in your code. Here's how you can do that:

this.myTimeout = setTimeout(() => { // Perform desired action }

When the component is no longer needed (for example, when the user navigates away), make sure to cancel the timeout. To achieve this, implement OnDestroy in your component class:

export class MyComponent implements OnDestroy{ ... }

Create a new method called ngOnDestroy:

ngOnDestroy(){
  clearTimeout(this.myTimeout);
}

Answer №2

After some tinkering, I finally cracked the code by incorporating something along the lines of

this.timerSubscription.unsubscribe();
into my ngOnDestroy().

The delay in grasping this solution stemmed from my interaction with modal windows, where navigation did not trigger destruction.

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

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

Issue with PrimeNG Calendar month picker functionality not functioning as expected

I recently integrated a PrimeNG code snippet for a month picker. Although it is functioning correctly, I noticed a discrepancy compared to the PrimeNG example - specifically, the year does not change when clicking on the arrow buttons. The ngModel, howev ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

The CORS policy specified in next.config.js does not appear to be taking effect for the API request

I am currently working on a Next.js application with the following structure: . ├── next.config.js └── src / └── app/ ├── page.tsx └── getYoutubeTranscript/ └── getYoutubeTranscript.tsx T ...

Achieving a persistent footer at the bottom of the page within Material Angular's mat-sidenav-container while using the router-outlet

I am looking to keep my ngx-audio-player fixed at the bottom of the screen, similar to what you see on most music streaming websites. I currently have a structure with divs and various elements for dynamic content and playing music. The issue is that the ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

reading an array of objects using typescript

Trying to retrieve an object from an array called pVal. pVal is the array that includes objects. I am attempting to obtain the value of "group" based on the id provided. For instance, if the id is equal to 1, it should display "VKC". Any assistance woul ...

Retrieve a specific item from the ngrx/store

My Reducer implementation in my Angular 2 app is designed to store state items related to price offers for Financial Instruments, such as stocks and currencies. This is the implementation of my Reducer: export const offersStore = (state = new Array<Of ...

Having trouble integrating CKEditor into a React Typescript project

Error: 'CKEditor' is declared but its value is never read.ts(6133) A declaration file for module '@ckeditor/ckeditor5-react' could not be found. The path '/ProjectNameUnknown/node_modules/@ckeditor/ckeditor5-react/dist/ckeditor.js& ...

Using regular expressions in TypeScript to declare modules

Is there a more efficient method to declare multiple modules in TypeScript? An example of the code I am trying to simplify is: declare module '*.png'; declare module '*.jpg'; declare module '*.gif'; declare module '*.svg ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

How can I collaborate on a component in Angular?

I'm currently developing an Angular application that utilizes a map feature powered by the Google Maps API. What I aim to achieve is the ability to freely move around the map to locate specific places, add markers, as well as edit existing markers, am ...

Encountering an error in Chrome where the property 'command' is undefined

Currently utilizing typescript and encountered an error in the chrome console: Error found in event handler for (unknown): TypeError: Unable to access property 'command' as it is undefined at chrome-extension://somethingsomethingsometh ...

Exploring the concept of individuality within front-end development

Would it be possible to manage identity directly on the front end using Angular's auth guard instead of setting up identity management on the server-side? The auth guard could handle all aspects of identity, even for smaller projects. For instance, in ...

Integrating a third-party plugin into an Angular 4 component

I am interested in integrating a 3rd party plugin into a component, such as CKEDITOR or even a jQuery plugin. While I am aware of the ng-ckeditor package, I prefer not to use it because I want the flexibility to incorporate any plugin in the future withou ...

Looping Through RxJS to Generate Observables

I am facing the challenge of creating Observables in a loop and waiting for all of them to be finished. for (let slaveslot of this.fromBusDeletedSlaveslots) { this.patchSlave({ Id: slaveslot.Id, ...

The problem with the Custom Select Component: Error Arises When Utilizing the Generic Type <T,> with a Comma as Opposed to <T> Without a Comma

I recently developed a unique custom select component that extends the standard HTML select element. During the process, I made use of a generic type to accommodate a wide range of data types, but encountered an unexpected error. The issue seems to persist ...

Is ConnectionServiceModule not compatible with Angular version 17.2.0?

I have encountered an issue in my Angular project that involves the compatibility of the ng-connection-service library with Angular Ivy. When I attempt to bring in the ConnectionServiceModule from the ng-connection-service into my Angular module, I am rece ...

Tips for hiding a <div> styled as a tooltip in an Angular application when the user clicks elsewhere

I am currently developing an Angular 7 application. One of the features I have implemented is an interactive icon that reveals an absolutely positioned tooltip component when clicked on by the user. However, I am faced with the challenge of making the too ...