Fetching URL from Right Before Logging Out in Angular 2 Application

I am struggling to capture the last active URL before logging a user out of my Angular 2 app. My goal is to redirect them back to the same component or page once they log back in. Currently, I am using

this.router.routerState.snapshot['url']
to retrieve the active URL; however, this always returns /login, which is the URL the user is sent to after being logged out. What I actually need is the URL right before the logout action. I have attempted to do this within my authenticationService's logout function:

logout()
{
    let activeUrl = this.router.routerState.snapshot['url'];
    console.log(activeUrl);
    this.apiService.logout();

    // Remove user from local storage 
    sessionStorage.removeItem('currentUser');
    console.log('User successfully logged out');

    // Emit event
    this.change.emit(this);
}

Despite logging the activeURL before calling this.apiService.logout(), I still receive /login in the console. Is this behavior expected? How can I work around this issue?

Upon further reflection, I realize that the problem may be due to calling the logout() function within the ngOnInit lifecycle hook of my login component, resulting in '/login' being captured. Therefore, how can I obtain the active URL just before the logout action occurs?

Answer №1

The documentation for Angular explains that the RouterState includes the RouterStateSnapshot, suggesting that calling toString() when logging to console will preserve a reference in your activeUrl even if it changes.

You can implement this by:

let activeUrl = this.router.routerState.snapshot['url'].toString();

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

I often find myself pondering the significance of objects such as [, thisArg]

At times, I delve into JavaScript code on MDN and come across some confusing syntax like [, thisArg]... for instance, arr.map(callback(currentValue[, index[, array]])[, thisArg]) In this scenario, I am aware that a callback function is required. But what ...

Creating a functional dropdown form in Ruby On Rails: A Step-by-Step Guide

Having an issue with implementing a dropdown form in the navigation bar of my Rails application. The problem arises randomly - sometimes it works smoothly, while other times I have to refresh the page for it to function properly. The Rails version being u ...

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

How can I eliminate text using regular expressions?

Greetings, I am seeking assistance with content removal using regular expressions. Below is the regular expression code I have written: reg = reg.replace(/\|.*?(\|)/g, ''); Input: One-1|two-2|Three-3|Four-4|Five-5 Six-6|Seven-7|Eig ...

JavaScript can be utilized to eliminate bootstrap tooltip attributes

Having trouble with adding and removing bootstrap tooltip attributes using JavaScript. The tooltip is added on mouseover, but not removed on mouseleave. The script adds the tooltip attributes on mouseover and should remove them on mouseleave. 'use s ...

Discover the solution for resolving the issue of HttpErrorResponse 405 not permissible

I am currently managing a website on a VPS that relies on Flask as the backend API server, Angular for the frontend, and Nginx as a reverse proxy. The Nginx has SSL installed, but I am encountering an issue where I can only connect to the Flask server usin ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Invoking an asynchronous method of the superclass from within an asynchronous method in the subclass

I'm currently developing JavaScript code using ECMAScript 6 and I'm facing an issue with calling an asynchronous method from a superclass within a method of an extending class. Here is the scenario I'm dealing with: class SuperClass { c ...

Use jquery and json to automatically populate select fields based on specific threshold values when they are changed

Looking for guidance on using jQuery to dynamically populate four select fields based on a four-level JSON array for a webshop, depending on threshold values. I'm seeking help with dynamically changing the selects only if the given value is greater t ...

Design your very own personalized Show Layout component

Currently, I'm in the process of creating a unique layout component to enhance the design of my Show page. I've encountered some inconsistencies with functionality, and my solution involves utilizing the Material-UI <Grid> component. While ...

Refresh the page and navigate to the last active tab using PHP and jQuery jTable

After a user clicks the submit button on a jquery-jtable form, I am trying to reload the page and navigate to the tab that was active before the reload. However, my current solution only reloads the page without navigating to the previous tab. The tabs are ...

Dynamically change the content of the DataTable by utilizing jQuery

I am facing an issue with updating a DataTable using jQuery when the contents of the table are modified. Initially, I have a HTML table with an empty tbody, which is populated dynamically based on selected filters such as select options. The table uses Dat ...

How can I simultaneously add two elements to a single node or to a node that does not exist in the JSON file?

I thought this would be simple, but I'm struggling to find the answer... var crit = { 'webshopId': webshopId, 'type': 'product'} }; I need to include sku.regularPrice = { $gte : parameters.minPr ...

Utilizing a dynamically created Stripe checkout button

Currently, I am attempting to integrate a checkout button from the Stripe Dashboard into my VueJS Project. I have a feeling that I might not be approaching this in the correct manner, so if you have any advice, I would greatly appreciate it. In order to ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

Is it possible to set environment variables in Next.js outside of the pages directory?

Are there alternative methods for setting environment variables outside of a pages directory in NextJS? I have a utility function that defines the base API route in one centralized location. However, since this is a utility function and not associated with ...

Display information from a Google Sheet onto a leaflet map based on specified categories

I am currently facing some challenges while creating a map with markers using data from Google Sheet and leaflet. Despite my efforts, I have encountered a few bugs that are proving to be difficult to resolve: Group Filtering - Although I can successfully ...

Ways to activate a function when the active tab in mat-tab is clicked

I am currently using angular 6 and I have set up a tab system with 3 tabs, each calling a different component. <mat-tab label="one"> <score-football ></ score-football > </mat-tab> <mat-tab label="second"> <score-hockey & ...

only one of the ng-bind-html elements on the page is functioning

I am currently working on an AngularJS application and encountered a problem with this block of code. Only the first ng-bind-html works for me: <div ng-bind-html='newsTitle'> <div ng-bind-html='newsDetail'></div> &l ...

Looking to include some extra padding when an item is displayed - jQuery

So, I'm working on a jQuery code snippet that controls the visibility of a rectangle element: $("#rectangle").hide(); $("#toggle-rec").click(function () { $("#rectangle").toggle(2000); }); This code hides the rectangle initially and toggles it ...