Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route?

This is a snippet from my app.routing.ts:

// other route configurations...

{ path: 'scrapers/:version', component: SingleScraperComponent, children: [
    { path: '', redirectTo: 'statistics', pathMatch: 'full' },
    { path: 'statistics', component: ScraperStatisticComponent },
    { path: 'targets', component: ScraperTargetsComponent },
]},

// other route configurations...

In the SingleScraperComponent, I have subscribed to Router events like this:

// component code

ngOnInit(): void {
    this._router.events.filter(event => event instanceof NavigationEnd).takeWhile(() => this.isAlive).subscribe(
        (event: NavigationEnd) => {
            console.log(event);
            if (event.url.indexOf('site-preview') === -1) {
               this._site.resetQuery();
            }
        }
    );
}

// component code

I am considering using OnDestroy, but I would need to determine the next route after destroying SingleScraperComponent.

Answer №1

After exploring the routerState snapshot, I was able to confirm the upcoming route:

ngOnDestroy(): void {
    if (this._router.routerState.snapshot.url.indexOf('site-preview') > -1) {
        console.log('Hello, from the required route!');
    }
}

If there is a clearer method to achieve this, please feel free to share.

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

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

The Zingchart final element continually switches colors, creating a mismatch with the legend

I'm facing an issue with my zingchart where the last element's color doesn't match with the legend and keeps changing unlike the others. Any suggestions on how to fix this? The rest of my code works fine. I am fetching data from a MySQL data ...

Submitting a form using AJAX without specifying the form ID when there is a change

I have a unique setup on my page where a table is created with each cell acting as a form. The goal is for these forms to submit when the input value changes (onchange) without refreshing the entire page. An example scenario would be allowing users to ent ...

Merge the data from various sections of a JSON object into a unified array

Upon completing an ajax call to a specific URL, I receive data in the form of a JSON object structured like this: {"field1":["val1","val2","val3",...,"valn"], "field2":["vala","valb","valc",...,"valx"]} My goal is to merge the values of field1 and field ...

Obtain varied results from the Knockout module

In my application, I am utilizing Knockout and Typescript. One of the classes in my code is as follows: class Address { State :string; ZIP: string; Street: string; } I want to create a component that will handle the updating of an object of ...

Mastering the Art of JSON Conversion for AngularJS

Is there a way to transform the following JSON data structure [{"categories":[{"id":"171","name":"Fashion"},{"id":"219","name":"Blog"}]}] into this format? [{"id":"171","name":"Fashion"},{"id":"219","name":"Blog"}] This change is necessary for proper ...

Switch between GeoJSON layers by using an HTML button within Mapbox GL JS, instead of relying on traditional links

I am currently developing a web map that requires toggling two GeoJSON layers on and off. In the past, I used Mapbox JS to accomplish this task by adding and removing layers with a custom HTML button click. However, I am facing some challenges in achieving ...

What is the best way to utilize jQuery.post in order to push JSON data to a php script?

I have a JSON object in my JavaScript code stored in the variable dataStore. I've confirmed that JSON.stringify is working correctly by testing it with console.log(). However, as someone new to jQuery and CGI applications, I may be missing something. ...

Updating the state in a different component using React and Typescript

The Stackblitz example can be found here I'm attempting to update the useState in one component from another component. Although it seems to work here, it's not functioning properly in my actual application. Here is a snippet of the app.tsx co ...

Python's Selenium encountering a NoSuchElementException with the error message "./ancestor-or-self::form"

Trying to create a Python script that allows me to input my credentials and tweet text in the Python console. The script should then log in and post a tweet using Selenium. Everything works fine, except for the final click on the Tweet button which is caus ...

Visualizing JSON data on D3.js graph axis

Below is a snippet of JSON data that I successfully plotted on a d3js graph, using it as the x and y axis: var data = [ { "count": "202", "year": "1590" }, { "count": "215", "year": "1592" }, { "count": "179", "year": "1593" } ]; Now, I am facing a chal ...

I'm looking for a way to customize the featureLayer style specifically for level 1 administrative areas in React, using the react-google-maps/api library in conjunction with the

I am currently working on a project in Next.js where I am trying to customize the coloring up to administrative_area_level_1 boundaries on a Google Map using the react-google-maps/api library. However, my struggle lies in finding the correct method to add ...

Ways to obtain the Map object from HTTPClient in Angular

When calling a REST endpoint, the return type is as follows: ResponseEntity<Map<String, List<Object>>> How can I handle this response on the Angular side? I attempted the following approach: let requiredData = new Map<String, Array&l ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

What could be causing my shape to not appear when I alter the variable name in three.js?

Recently, I encountered an interesting issue with some code I found on a tutorial website. The code worked perfectly when I used the variable 'canvas', but when I changed it to something else like 'canvas2', it caused unexpected behavio ...

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

Encountering the "TypeError: fetch failed" error message while attempting to utilize @vercel/og in conjunction with Astro

I've been experimenting with the @vercel/og package in order to set up an API route for generating open graph images. As I work with an Astro application, I simply followed the vercel example that is framework agnostic: // api/og.ts import { ImageRes ...

Jest test encountering an issue where FileReader, File, and TextDecoder are not defined

While I have primarily used Jasmine for tests in the past, I am now experimenting with Jest. However, I have encountered an issue where classes like FileReader, File, and TextDecoder are not defined in my tests. How can I incorporate these classes with t ...

Ways to conceal and reveal a different section at the same time (like an accordion)

Looking for guidance on implementing an accordion-style functionality, where clicking a navigation link hides one section and reveals another seamlessly with automatic scrolling to the start of the section (end of the navigation). Any tips or starting poin ...

Conflict arising from duplicated directive names in AngularJS

Hey there, I've got a question for the experts. How can I prevent conflicts with directive names when using external modules? Right now, I'm utilizing the angular bootstrap module, but I also downloaded another module specifically for its carouse ...