Checking for queryParam changes in Angular before ngOnDestroy is invoked

I am looking to conditionally run some code in the ngOnDestroy function depending on changes in the current route.

Specifically, when the route changes from /foo to /login?logout=true, and this change is initiated outside of the Foo component.

In the ngOnInit method, I am subscribing to query parameter changes to correctly update the loggingOut flag.

The issue I'm facing is that ngOnDestroy is being called before the query parameter handler, resulting in the loggingOut flag having the wrong value.

export class FooComponent implements OnInit, OnDestroy {
    
    loggingOut = false;

    constructor(private route: ActivatedRoute) {}

    ngOnInit(): void {
        this.route.queryParamMap.subscribe(queryParams => {
            this.loggingOut = queryParams.get('logout') === 'true';
        });

    }

    ngOnDestroy(): void {
        if (this.loggingOut) {
            // do this
        } else {
            // do that
        }
    }
}

It appears this behavior is intentional from a lifecycle perspective, so my question is:

  • Is there a way to check route changes before ngOnDestory is called?

If possible, please provide a link to documentation that explains how lifecycle hooks, especially ngOnDestory, are triggered in relation to navigation changes.

Thank you.

Answer №1

One issue I'm facing is that ngOnDestroy is being called before the next queryParam handler.

componentDestroyed = false;

ngOnInit(): void {
    this.route.queryParamMap.subscribe(queryParams => {
        if (!this.componentDestroyed)
            this.loggingOut = queryParams.get('logout') === 'true';
        else {
           // Place the necessary logic here to handle ngOnDestroy prematurely
        }
    });

}

ngOnDestroy(): void {
    this.componentDestroyed = true;
}

Could this potentially solve the issue at hand?

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

Converting Python code into JavaScript for use on an iPhone device

Having a web application with backend developed in Python (using Django) and front end in HTML5 & JavaScript, where Python generated data is transferred to JavaScript/HTML through JSON. Now, I want to transform it into a mobile application, starting with ...

Developing custom node modules for efficient exporting and importing using the Babel transpiler

In a separate project, my goal is to replicate the following structure: import { FuncA, FuncB, FuncC } from @myorg/hellow For an internal project, I am creating my own node module with the folder organization of hellow as outlined below: ...

Unlocking the potential of Node.js: Mastering the art of passing extra parameters in async

Exploring JavaScript and Node.js I'm currently working on developing some javascript / node.js code with a specific purpose in mind: To retrieve keys from a redis database and extract relevant information from the hash. Here is an example of what ...

Ways to retrieve output from a JavaScript function

How can I successfully return the result from response.on within the signIn function? const signIn = async (password) => { var request = new DeviceAuthQuery(); request.setPassword(password); var response = client.authenticate(request, {}, (err, ...

Cut off the initial characters in the URL's hash component

Hey there, I'm currently working on a task that involves removing a specific part of a URL string. Here's the scenario: if (window.location.hash == '#super-super-product') { change.window.location.hash.to.this: #product // this i ...

Tips for utilizing a variable from a function in one file within a function in another file

Having trouble using the variable counter from one function in a different file? In the first function, I defined counter without using "var" thinking it would make it a global variable. But for some reason, it doesn't seem to work. Help needed! //fun ...

Angular 4 get request using query strings

The initial code block is performing as anticipated fetchQuotes(): Observable<Quote[]> { return this.http.get(this.url) .map((res: Response) => res.json()) .catch((error: any) => Observable.throw(error.json().error || &apos ...

Check off all checkboxes and send their values to an AJAX script using a table

I currently have a table set up with checkboxes in the first column. By checking these boxes, an AJAX script is triggered that updates a PHP session variable with the selected values. This functionality is working smoothly. However, I am now looking to enh ...

<fieldset> triggering onChange event in React form

I am facing an issue with my React component where multiple onChange functions are not getting fired. After some debugging, I realized that the problem lies with the fieldset element within the form. Removing the fieldset allows all onChange functions to w ...

Rotate images with animation using Javascript

Seeking assistance with a swinging motion using two simple functions in Javascript. As a newcomer to the language, I am looking for guidance to achieve my goal. First function: function up() { imgObj.style.left = parseInt(imgObj.style.transform = 'r ...

Include the model.obj file into the three.MESH framework

I am a beginner in three.js and I am developing an augmented reality application on the web to showcase plates of food. Currently, I have successfully displayed a cube. However, when I attempted to display a model.obj instead of using geometry and material ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

Unidentified file: Error reading property 'filename'

I have a function that retrieves the file name. The file name is displayed in an input field, but the background color of the input field is only visible when a file is selected and the file name is populated there. I would like the background color to b ...

Issues with Firebase Cloud Messaging functionality in Angular 10 when in production mode

Error: Issue: The default service worker registration has failed. ServiceWorker script at https://xxxxxx/firebase-messaging-sw.js for scope https://xxxxxxxx/firebase-cloud-messaging-push-scope encountered an error during installation. (messaging/failed-ser ...

Updating a string in JavaScript by dynamically adding values from a JSON object

In my current function, I am making a request to fetch data and storing it as an object (OBJ). Afterwards, I make another request to get a new URL that requires me to update the URL with values from the stored data. The information saved in the object is ...

Understanding the Event Context of Elements using Browser Development Tools

I'm currently investigating the functionality of the search feature on the React Documentation page: https://reactjs.org/ . It's known that they utilize DocSearch, but I'm interested in understanding the inner workings. At the moment, I&ap ...

Combine Typescript files from a dependent module to aid in debugging within a Next.js application

Trying to debug a project written in Typescript using Next.js, but facing issues with bundling TS files from a local dependent common library. Only JS files are included, which is not sufficient for debugging. The goal is to bundle all TS files from the w ...

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

What's causing my pug file to not show the data I retrieved?

In my index.js file, I have confirmed that the data is successfully retrieved using console.log. However, when I attempt to display this data in my view, I encounter an error that says: "Cannot read property 'feedUrl' of undefined. The followin ...

Using AngularJS to prefill a HTML5 date input field with a default value

Is there a way to bind the default value generated in moment to both the date and time input fields? I have tried using ng-model and directly binding it to the value attributes, but without success. Any suggestions on how to make this work? Edit: Addition ...