Retrieving the Previous URL Before Logging Out in an Angular 2 Application

Within my Angular 2 application, I am facing a challenge in storing the last active URL before a user logs out. The goal is to reload this URL once the user logs back in. However, this task has proven to be quite troublesome. Take a look at the logout function in my authenticationService:

logout()
{
    let lastUrl = this.getActiveUrl();
    console.log('Url before logout: ', lastUrl);

    this.apiService.logout();
}

It is important to note that the "lastUrl" variable, which calls this.getActiveUrl(), works as follows:

getActiveUrl()
{
    let activeUrl = this.router.routerState.snapshot['url'];
    console.log('activeUrl: ', activeUrl);
    return activeUrl;
}

Strangely enough, even though "lastUrl" appears BEFORE this.apiService.logout(), it still ends up displaying "/login". This is confusing because "/"login" is actually where I get redirected immediately after logging out.

So, here are my questions:

If this process is synchronous, why doesn't the correct URL display here? What am I overlooking? And how can I retrieve the active URL right before the logout event occurs and redirects to '/login'?

UPDATE: Following a suggestion from a commenter, I attempted to store the URL in localStorage rather than a local variable like so:

logout()
{
    localStorage.setItem('returnUrl', JSON.stringify(this.router.routerState.snapshot['url']));

    this.apiService.logout();
}

However, when I attempt to retrieve this value using localStorage.returnUrl, I still end up with "/login".

Answer №1

Big shoutout to @Sam for the helpful localStorage tip. I can't believe I didn't think of that sooner! The solution ended up being simpler than I thought. All I had to do was utilize RouterStateSnapshot within my canActivate() function in AuthGuardService, saving the value to localStorage. Then, when it came time to re-authenticate and log back in, I could easily retrieve that stored value:

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    {

        // Retrieve content ID from route
        let contentId = Object.getPropertyValueAtPath(route, 'data.contentId');

        // Save the last active URL before logout for redirection on re-login
        localStorage.setItem('returnUrl', JSON.stringify(state.url));

        // DO OTHER STUFF...

    }

In the login component, all I needed to do was fetch that saved value...

login(response)
{
    this.loading = true;

    this.authenticationService.login(this.model.username, this.model.password, function (results)
    {
        if (results.data && results.ok === true)
        {
            this.returnUrl = JSON.parse(localStorage.getItem('returnUrl'));
            this.router.navigate([this.returnUrl || '/']);
            console.log('ReturnURL Value is: ', this.returnUrl);
            this.reset();
        }
        else
        {
            this.alertService.error(null, response);
            this.loading = false;
        }

    }.bind(this));
}

Answer №2

The events are occurring simultaneously. Yet, as you log an object pointer, it may differ when you check the object in the console due to the route changing. To address this, I recommend utilizing local storage for storing the router snapshot. This approach avoids encountering the pointer inconsistency observed in the console.

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

Getting unique results from a knex.js INNER JOIN operation

Two tables, metadata and view_events, each have columns for config_id and config_type. The goal is to retrieve all unique view_events based on a user's email address, distinct by config_id and config_type, ordered by timestamp in descending order, lim ...

Utilizing Jquery for transmitting and receiving data

As a newcomer to application development, I have been struggling with figuring out how to send and retrieve data using the latest version of JQuery. My main concern is ensuring that the functionality I implement is compatible with all browsers. While I ha ...

The React-loadable alert indicated a discrepancy in the text content

Utilizing react-loadable for dynamic JS module loading is part of my process. With server-side rendering already set up and functioning correctly for react-loadable, I am encountering an issue on the client side. Upon page load, a warning message appears i ...

React's input onChange event does not trigger for the second time. It only works the first time

Recently, I developed a React JS application to import images from external sources and process them. To handle the user's onChange event, I utilized the onChange attribute to execute my handleChange function. However, I encountered an issue where it ...

The Process of Deploying Angular 4 Applications to Production

My colleague and I recently had a thorough discussion about the best approach to deploy our Angular 4 app on a production server. I would greatly appreciate practical advice and guidance from the community regarding this issue. Thank you in advance! Prem ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Merging SCSS and CSS into a unified file using WebPack

Trying to grasp webpack as a beginner is proving to be quite challenging for me. I'm struggling with the concept of merging multiple scss and css files together using webpack, after transpiling the sass. Unlike gulp, where I could easily transpile sa ...

Deactivate the date when it reaches 8 in the current date count using ajax, php, and mysql

I want to prevent users from selecting a specific date after it has been chosen 8 times. Currently, when the date is selected for the 9th time, an alert box pops up. Instead of the alert box, I would like to disable that particular date selection altogethe ...

Codeigniter 3 and Ajax: Troubles with receiving post data

I'm struggling to successfully send some data via Ajax to save it inside a controller. Unfortunately, I am unable to retrieve the posted data inside my controller as it always appears empty. Here is my basic Ajax code that just doesn't seem to w ...

What is the best way to arrange objects in an array by date using Angular 4?

My array of objects is structured like this : this.filteredData = [ {'id': 1, 'date': '04-05-2018'}, {'id': 2, 'date': '29-03-2018'}, {'id': 3, 'date': '03-04 ...

Hot Module Replacement (HMR) for Redux Toolkit in React Native does not trigger updates in

TL;DR: Setting up the Redux Toolkit store in React Native for HMR correctly refreshes the app when changes are made, but the behavior of the reducer remains unchanged! Despite the announcement about React Native Reloading, it seems that the steps outlined ...

In the past, it was impossible to access all properties simultaneously from a TypeScript union

Recently, I purchased an online course that I had put off watching until now. In the course, it specifically mentioned that certain code in TypeScript was not allowed: type Name = { name: string } type Age = { age: number } type UnionBoth = Name | Age co ...

The error encountered is: `Exception: startDate.getTime is not a valid function

const [currentDate, setCurrentDate] = useState(new Date()); const fetchDataFromAPI = () => { let timeStamp = Number(currentDate.getTime()); axios.get( `https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD,EUR& ...

What is the best way to clear a dynamically populated form using ajax?

Is there a way to clear a form that has been loaded via ajax using only JavaScript or jQuery? I attempted document.forms[0].reset(); and $('#new-staff-form')[0].reset();, but both resulted in an undefined error. Update <div class="box col-md ...

Ensuring the safety of ajax GET/POST communication between client and server

Let's say I'm working with a specific API and my file server.php is responsible for connecting to the API service. On the client side, I am using an AJAX call like this: $http({ url : 'server/server.php', method : &ap ...

Received undefined data from Angular2 service

I have encountered an issue while working with Angular2 and retrieving data from a json file using an injectable service. Initially, when I console the data in the service, it displays correctly. However, when I retrieve the data in my component through a ...

What are the best strategies for managing npm dependencies alongside other packages?

I am working on an Angular app that has the following dependencies: "dependencies": { "personalUiLibrary": "1.0.0" }, "devDependencies": { "tailwindcss": "^2.2.7" } In the personalUiLibrary p ...

JavaScript and HTML - specify the location in the html document where the JavaScript script will be displayed

I'm a beginner when it comes to JavaScript. I am trying to make sure that my HTML page remains unchanged while JavaScript text is displayed in a specific location without refreshing the entire page. To trigger a JavaScript function via a button on a ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

Iteratively modify each essential attribute of a JSON object

In my data set, I have moisture levels recorded at various timestamps in a JSON object: { "values": { "21-Aug-2020 20:28:06:611591": "58.59", "21-Aug-2020 20:28:09:615714": "71.42", "21-A ...