When another page is refreshed, Angular routing redirects back to the home page

Within my application, there is a homepage that appears after the user logs in, along with some other pages. However, I've encountered an issue where when I navigate to one of these other pages and then refresh the page, it redirects me back to the homepage. Here are my Routes:

const routes: Routes = [
  {
    path: '', redirectTo: '/home', pathMatch: 'full'
  },
  {
    path: 'login',  component: LoginComponent 
  },{
    path: 'list',  component: ListComponent, canActivate : [AuthGuardService]
  },{
    path: 'home', component: HomeComponent, canActivate : [AuthGuardService]
  },{
    path: 'detail/:id',  component: HomeComponent, canActivate : [AuthGuardService],
  },{
    path: '**', redirectTo: 'login' ,pathMatch: 'full'
  }
];

The app-component contains the router outlet

<div [ngClass]="{'container': (isLoggedIn$ | async), 'mt-2': (isLoggedIn$ | async)}" class="h-100">
    <router-outlet></router-outlet>
</div>

What I expect is for when I am on the "list" page (localhost:4200/list) and I refresh the page, it should remain on that page. Instead, it currently redirects me to localhost:4200/home. Additionally, clicking on a list item should take me to localhost:4200/detail/itemId, but it always sends me back to the home page. Thank you

Edit made with AuthGuardService:

export class AuthGuardService implements CanActivate {
  constructor(private route : Router, private store: Store<AppState>) {}

  canActivate() {
    return this.store
      .pipe(
          select(isLoggedIn),
          tap(loggedIn => {
              if (!loggedIn) {
                this.route.navigate(['login']);
              }
          })
      )  
  }
}

I have introduced the login effect

login$ = createEffect(() =>
        this.actions$
            .pipe(
                ofType(userActions.login),
                tap(action => {
                    localStorage.setItem('userInfo',
                    JSON.stringify(action.user))
                    this.router.navigate(['home']);
                })
            )
    ,{dispatch: false});

SOLUTION:

After spending several hours debugging, I finally discovered the solution. Essentially, I removed this.router.navigate(['home']); from the AuthGuardService and instead placed it in the login function of the component as soon as the user logs in. By placing this.router.navigate(['home']); in the AuthGuardService, the guard was triggered every time I refreshed the page, leading to constant redirection to the home page. That's all. Thank you

Answer №1

The arrangement of routes plays a crucial role as the Router implements a first-match wins strategy in route matching. Therefore, it is recommended to prioritize more specific routes over less specific ones.

  • Begin with listing routes featuring a static path.
  • Follow this up with an empty path route that serves as the default route match.
  • Place the wildcard route last as it matches all URLs.

The Router will only select the wildcard route if no other routes match beforehand.

Reference: https://angular.io/guide/router#route-order

To modify the order, make the following adjustments:

const routes: Routes = [
  {
    path: 'login',  component: LoginComponent 
  },{
    path: 'list',  component: ListComponent, canActivate : [AuthGuardService]
  },{
    path: 'home', component: HomeComponent, canActivate : [AuthGuardService]
  },{
    path: 'detail/:id',  component: HomeComponent, canActivate :  [AuthGuardService],
  }
  {
    path: '', redirectTo: '/home', pathMatch: 'full'
  },
  ,{
    path: '**', redirectTo: 'login' ,pathMatch: 'full'
  }
];

Answer №2

It seems like you've resolved your problem, but I wanted to share my experience as it took up a few days of my time. In my situation, we needed a specific route to open in a new tab unlike the other routes.

<a *ngIf=link.externalRoute href={{link.route}} target="_blank">

However, every time I tried to open the new tab, it kept redirecting me back to the home route. I went through my routing setup, authentication process, auth guards, and even checked for manual navigations in the code, but couldn't pinpoint the issue.

Eventually, I discovered that the issue was with the route name itself. I had mistakenly used 'target-route' instead of '#/target-route'! The absence of the hash symbol made the route invalid, causing it to default back to the home route.

This solution may only apply if you are using hash in your Angular routing system, but hopefully, it can be useful to someone in the future.

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

Guide on triggering a function with the Enter key in Angular 9

A button on my Angular component currently triggers a method with a (click) event, but I also want the same method to be triggered if the user presses the enter key in the input box. This gives the user flexibility. Below is the HTML code for the input an ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

What is the method in TypeScript for defining a property in an interface based on the keys of another property that has an unknown structure?

I recently utilized a module that had the capability to perform a certain task function print(obj, key) { console.log(obj[key]) } print({'test': 'content'}, '/* vs code will show code recommendation when typing */') I am e ...

Comparing Angular global variables: when to use static readonly in service class versus const

Which method is the better choice? @Injectable({ providedIn: 'root' }) export class MyService { static readonly VALIDITIES = new Map<number, string>([ ... ]); ... } OR: const Validities = new Map<number, string>([ .. ...

Unable to modify the Express Request User type, however, I have the ability to incorporate new attributes to Request object

Encountering a familiar issue with what appears to be a simple fix. The Express Request object includes a user property that is specified as Express.User (an empty object). Attempting the common approach to redefining it: // index.d.ts import { User as P ...

There was an error in processing node npm due to Z_DATA_ERROR with error code errno -3, indicating an

When attempting to run my TypeScript project using tsc, I encountered the following error: Found 181 errors in 4 files. Errors Files 1 node_modules/@types/eslint-scope/node_modules/@types/eslint/helpers.d.ts:1 1 node_modules/@types/eslint/hel ...

The values of object keys are printed in a random order

Hey everyone, I have an object that looks like this var dates = { '2021-09-15': 11, '2021-09-16': 22, '2021-09-17': 38, '2021-09-18': 50, '2021-09-19': 65 }; I am trying to display the valu ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

The current directory does not belong to a Cordova project

Upon executing ionic cordova run browser --verbose within the main directory of my Ionic4 project, I encounter the error message "Current working directory is not a Cordova-based project." as shown below. I've observed that the command generates a "w ...

Struggling to capture the error thrown by the subscribe method in Angular using RxJs

In following the most recent tutorial, I learned about using pipe, tap, and catchError to intercept the result. This is what I currently have: getStatus(): Observable<boolean> { return this.http.get<boolean>('/status').pipe( ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Unit testing in Angular 2: Triggering hover events

In my setup, I have a template for a specific component (MyCmp) that looks like this <template ngFor let-r [ngForOf]="range" let-index="index"> <span>{{ index < 5 ? 'Y' : 'N' }}, {{r.data}}</span> <i (mousee ...

Utilizing TypeScript for various return types with the same parameters

Exploring TypeScript Signatures In an effort to embrace TypeScript fully, I am implementing strongly typed signatures in my Components and Services, including custom validation functions for angular2 forms. I have discovered that while function overloadi ...

Trouble with running the "npm run tsc" command in Angular 2 beta

I'm facing an issue with compiling my Typescript using the command npm run ts. What's odd is that I can successfully compile and run it by running npm start. Below is the log: 0 info it worked if it ends with ok 1 verbose cli [ 'node' ...

Having trouble retrieving information from a JSON object? Unable to retrieve property 'company_about' of an undefined object?

Here is the JSON data I have: [ { "id": 1, "job_id": 1, "company_profile": "Sales and Marketing", "company_about": "Established in 1992 , it is a renouned marketing company", "company_product": "Ford,Mustang,Beetle", "key_skills": ...

Issue with React Redux: Store dispatch not causing component update

I have recently implemented React Redux in my project, but I seem to be encountering some issues. Despite changing the state, the value remains the same. I attempted to use useStore(), but it does not take any parameters. Can anyone provide insight into wh ...

What is the best way to use a single schema in MongoDB to create an object with an array?

Currently, I am working on creating a single Schema for Author with their respective quote. Here's what my model looks like at the moment: const mongoose = require("mongoose"); const AuthorSchema = new mongoose.Schema({ name: String, quote: ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

Show various perspectives depending on the circumstances

I am looking for a solution to display a different component if my ngFor loop returns null. <ion-select interface="popover" [ngModel]="selectedKidId"> <ion-option *ngFor="let kid of kids" [value]="kid.id">{{kid.name}}</ion-option& ...

Employing a general-purpose function in a recursive manner

My function that removes properties from an object and returns a new one works fine, but it runs into issues when dealing with nested arrays of objects. How can I tackle this challenge? interface User { id: number; name: string; items?: User[]; } co ...