When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing paths are defined in my root routing file:

{ path: 'home', component: HomeComponent, canActivate: [AuthGuard], data: {contentId: 'home-page'} },
{ path: 'contacts', component: ContactsComponent, canActivate: [AuthGuard], data: {contentId: 'contacts-page'} },

However, I have noticed that when I right-click on a link and select "Open Link in New Tab" while trying to navigate to a different component, instead of loading the correct component in the new tab, the page redirects to the login page. This behavior only occurs when using the "Open Link in New Tab" option in Chrome.

The route for my login component is as follows:

{ path: 'login', component: LoginComponent },

To provide more context, the only redirection logic in my root routing file is set up to redirect to the home component when a route is not recognized:

{ path: '**', redirectTo: 'home' }

For instance, here is what the link for the "contacts" route looks like: http://localhost:4200/contacts

I am unsure if this issue is related to the browser settings or if it stems from default Angular behavior. I am seeking guidance on how to identify and resolve this issue.

Initially, I suspected that the problem might be related to the AuthGuard, but even after removing the AuthGuard protection from the "contacts" link, the issue persists and the page still redirects to the login component when opened in a new tab.

Below is a snippet of the code implemented in my login component:

    constructor(private router: Router,
                private route: ActivatedRoute,
                private authenticationService: AuthenticationService,
                private alertService: AlertService,
                private idle: Idle)
    {}

    ngOnInit()
    {
        // Code for resetting login status
        this.authenticationService.logout();

        // Handling return url assignment 
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    login(response)
    {
        // Login functionality
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data =>
                {
                    this.router.navigate(['/']);
                    this.reset();
                },
                error =>
                {
                    this.alertService.error(error, response);
                    this.loading = false;
                });
        this.authenticationService.username = this.model.username;
    }

    reset()
    {
        // Resetting user session
        this.idle.watch();
        this.idleState = '';
        this.timedOut = false;
    }
}

The relevant sections of the authenticationService utilized in the login component are depicted below:

login(username: string, password: string)
{
    // Processing login data
}

isAuthenticated()
{
    // Function to authenticate user session
}

logout()
{
    // Logging out user session
}

Answer №1

One solution discussed in the comments is to modify your AuthenticationService by replacing sessionStorage with localStorage. Unlike sessionStorage, data stored in localStorage persists even when the tab is closed.

If you'd like more information on this topic, check out:

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

Using data analysis to customize the appearance of boundaries across various map styles - Google Maps Javascript API V3

Utilizing data-driven styling for boundaries in Google Maps Javascript API V3 is a fantastic feature that appears to be compatible with all map types such as terrain, satellite, and hybrid. Nevertheless, I have encountered difficulties in making it visible ...

Create a scrollable div within a template

After discovering a template that I want to use for my personal project, I noticed a missing element... There's a div where content can be added. That's fine, but what if I add more content than fits in the space provided? The whole website beco ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

Querying MongoDB to locate an element within an array is a common task

I need help with writing a mongoose query to select a specific object from the "cartItems" array in my mongodb database and update its "qty" and "price" fields. Here is the data: { _id: new ObjectId("634a67e2953469f7249c9a7f"), user: new ObjectId("634 ...

Having difficulty attaching events to Bootstrap 3 button radios in button.js

Struggling with extracting the correct value from a segmented control created using the radio button component of button.js in Twitter Bootstrap 3. Upon binding a click event to the segmented control and running $.serialize() on its parent form, I noticed ...

Discover the location by determining the distance from established points

Before I get redirected to this particular question, let me clarify that while I've come across it, I am unable to comprehend its content (I wish I could). What I'm really seeking is a straightforward method (bearing in mind my limited math skill ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Creating a data structure using jQuery/JavaScript when submitting a form - a guide

Currently, I am attempting to gather form input values and organize them into an array of objects that will then be sent to MongoDB. However, I am facing difficulty in figuring out how to include an array within the objects (refer to the comment in the cod ...

Utilizing a keycode within the jQuery plugin without the need to explicitly pass it through options

I am currently working on developing a custom jQuery plugin. My goal is to be able to check the keyCode within the plugin without needing to pass it through as an option parameter. Below, you can see the code snippet that I'm using. It's a bit c ...

How can the CORS issue be resolved when sending a form from a client to an AWS API gateway function?

Within my front end React application, I am looking to implement a contact form that will submit data to a Lambda function via an API Gateway with a custom domain attached. The frontend operates on the domain dev.example.com:3000, while the API Gateway is ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

Creating personalized properties for a Leaflet marker using Typescript

Is there a way to add a unique custom property to each marker on the map? When attempting the code below, an error is triggered: The error "Property 'myCustomID' does not exist on type '(latlng: LatLngExpression, options?: MarkerOptions) ...

"Experience the latest version of DreamFactory - 2.0.4

I'm encountering a 404 error when I send a request to my new DSP. GET http://example.com/api/v2/sericename/_table/tablename 404 (Not Found) Upon checking the Apache error.log, I found this message: ... Got error: PHP message: REST Exception #404 &g ...

Create a cylindrical HTML5 canvas and place a camera view inside the cylinder

I have a unique project in mind that involves creating an HTML5 canvas cylinder with the camera view at its center. The walls of the cylinder will display images, and the entire structure should be able to rotate and zoom. If anyone has any advice on how ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...