Redirect to the identical component once the session has ended

I have a token-based API that expires after 10 minutes of user inactivity. When the token is changed due to idle time, an error response is received from the API and the user is redirected to the login page.

Currently, when the user logs in again, they are redirected to the main page. However, I want the user to be able to log back into the same page they were on before.

Is it possible to use sessions to store the active router value so that after the session expires, the user can navigate back to the exact location they left off?

For testing purposes, I have created an application on Stackblitz, where I simulate timeout navigation to the login page after 10 seconds.

For example, if the user clicks login, goes to the user page, then navigates to the dashboard component, but is redirected to the login page after 10 seconds, I want them to return to the dashboard component upon logging in again.

Login Page

<div id="login">
        <div class="container">
            <div id="login-row" class="row justify-content-center align-items-center">
                <div id="login-column" class="col-md-6">
                    <div id="login-box" class="col-md-12">
                        <form id="login-form" class="form" action="" method="post">
                            <h3 class="text-center text-info">Login</h3>
                            <div class="form-group">
                                <label for="username" class="text-info">Username:</label><br>
                                <input [(ngModel)]= "userName" type="text" name="username" id="username" class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="password" class="text-info">Password:</label><br>
                                <input [(ngModel)]= "password" type="password" name="password" id="password" class="form-control">
                            </div>
                            <div class="form-group">
                                <input type="submit" (click)="formValidation()" name="submit" class="btn btn-info btn-md" value="submit">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

Login.component.ts

formValidation(){
    console.log(this.userName);
    console.log(this.password);
    this.router.navigate(['user'])
  }

Please suggest the best approach for handling router navigation after the session expires. Link to edit Stackblitz

Answer №1

My approach involves handling error responses from the API in a specific way. When an error is detected, I immediately redirect the user to the login page using this code snippet: this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});

In this scenario, "state" refers to RouterStateSnapshot imported from @angular/router.

Once on the login page, I retrieve the return URL query parameter using the following line of code: this.returnUrl = this.route.snapshot.queryParams['returnUrl'];

In this context, "route" corresponds to ActivatedRoute imported from @angular/router.

Upon successful login authentication, the user is directed to the designated return URL with this command: this.router.navigate([this.returnUrl]);

The term "router" signifies the Router component imported from @angular/router.

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

Automatically adding Typescript property decorator to the prototype

Looking to implement a feature in Java/TypeScript where I can automatically add properties without writing them into the constructor. As a beginner, my attempt might not be perfect. Here's what I have so far... The idea is to achieve something like t ...

Converting an Observable of Object arrays into a regular Object array within component files

I understand that pipes can be used within views to achieve this, but I am unsure of how to implement it within a component file. drop(event: CdkDragDrop<string[]>) { this.posts$.subscribe((posts) => { console.log(posts); //This is the ...

Acquiring the download link for Firebase Storage in Angular 2+ technology

reference: AngularFireStorageReference; task: AngularFireUploadTask; uploadState: Observable<string>; uploadProgress: Observable<number>; downloadLink: Observable<string>; beginUpload(event) { const id = Math.floor(Math.random() * 1000 ...

Centered title in side menu for Ionic 3

I recently utilized the Ionic CLI to create an Ionic project. The version I am working with is Ionic 3. Currently, I am facing a challenge in centering the title image. Any assistance on this matter would be greatly appreciated. <ion-menu [content]=" ...

What is the significance of importing from the parent directory in TypeScript?

During my TypeScript project in VSCode, I decided to import an interface from another file. To my surprise, when I allowed VSCode to automatically insert the import statement, it appeared as follows: import { IOAdapter } from '..'; I was actual ...

Upon initial page load, the distinctUntilChanged() function will not be triggered

Upon loading a page, I initiate the following method and utilize the returned list in a dropdown menu. The tap and switchMap functions are run as expected, however, the distinctUntilChanged function does not execute upon page load. Once the page is loade ...

Styling your Angular project with CSS

I have a folder called about which contains a file named about.component.css . I want the background-color to be set to aqua only for the page about.component.html. When I try setting the background-color in about.component.css like this: body { backg ...

I'm interested in utilizing Angular 2 to parse a CSV file and showcase the data in a table

Hello everyone, I am new to Angular 2/4 and I am trying to parse a CSV file and display the data in a table on a webpage. I have attempted some code, but the data only gets displayed in the console, not on the webpage itself. Can anyone help me out? hand ...

Writing a condition using *ngFor to validate two values

I am currently utilizing angular 7. Within my Component, I have a Stock Array as displayed below: private stocks:any = []; [{ "scripcode": "M&M", "open": "671.95", "high": "676.90", "low": "661.60", "exchange ...

Upgrade Angular from 12 to the latest version 13

I recently attempted to upgrade my Angular project from version 12 to 13 Following the recommendations provided in this link, which outlines the official Angular update process, I made sure to make all the necessary changes. List of dependencies for my p ...

Ways to bypass HostListener in Angular 2

In the process of developing a page with animations triggered on scroll, I encountered the challenge of ensuring that the animations only occur when the corresponding element is visible on the viewport. Utilizing Angular2 for this task led me to investigat ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

The installation of @types/jquery leads to an unnecessary global declaration of $

In my package.json file, I have the following dependencies defined: { "dependencies": { "@types/jquery": "^3.5.5", } } This adds type declarations through @types/jquery/misc.d.ts, including: declare const jQuery: JQue ...

What steps should I take to resolve the issue where AddJsonOptions does not have a definition for SerializerSettings

Desperately seeking help, I've been scouring the internet for a solution to no avail. It's probably something simple, but I just can't seem to figure it out. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .Ad ...

Tips for Monitoring Service Worker (sw-precache) Updates within Angular 4

Within the code of the SW-Precache demo, there is a specific line that triggers a console log indicating when "the old content has been removed and fresh content added to the cache." The accompanying comments suggest this as an opportune moment to inform u ...

Error! Unable to Inject ComponentFactoryResolver

Recently, I attempted to utilize ComponentFactoryResolver in order to generate dynamic Angular components. Below is the code snippet where I am injecting ComponentFactoryResolver. import { Component, ComponentFactoryResolver, OnInit, ViewChild } from "@an ...

Styling and theming in PrimeNG

Seeking advice on how to customize the appearance of the background for the primeNG panel component. I attempted to override the styling using the specific names in my scss file for the component, but it did not work. I also tried inline with <p-panel ...

Utilizing Typescript to Transfer Data from Child to Parent in React

Attempting to pass data from a Child Component to a Parent component using Typescript can be challenging. While there are numerous resources available, not all of them delve into the TypeScript aspect. One question that arises is how the ProductType event ...

Email Verification using AngularFire2

Currently, I am using AngularFire2 for user authentication through Firebase. One feature I have incorporated allows users to update their email address. firebaseUser: firebase.User firebaseUser.updateEmail(newEmail).catch((data) => {... Now, I want ...

Setting up TypeScript to use a connected component within a parent component: A step-by-step guide

I have created a connected component that utilizes mapStateToProps and mapDispatchToProps to inject the properties into the Props without the need for the parent to inject anything. However, TypeScript raises an error when I import it into another componen ...