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

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

The push action in NavController is not displaying Google Maps as expected

Trying to display a map upon clicking a button is proving challenging for me. It appears that the function NavController.push() does not work as expected, while NavController.setRoot() does. Despite not encountering any errors, I am unable to identify the ...

You cannot assign multiple properties with the same name to an object literal

I am facing an issue with two validator functions in my TypeScript file. The first validator checks if a user enters a new password same as the old one, displaying an error if so. The second validator ensures that "new password" and "confirm password" must ...

Tips for enhancing the FastifyRequest interface with a new property without erasing existing information in a declaration file

What is the method to integrate a property into an interface via declarations, while avoiding full object overwriting? declare module 'fastify' { interface FastifyRequest { user: User; } } //auth.ts ... const user = jwt.verify( ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

Interactive Bootstrap 4 button embedded within a sleek card component, complete with a dynamic click event

I am trying to create a basic card using bootstrap 4 with the following HTML code. My goal is to change the style of the card when it is clicked, but not when the buttons inside the card are clicked. Currently, clicking on the test1 button triggers both ...

Angular 16 brings a revolution in routerLink behavior

Previously, when I was using angular < 16, my routes configuration looked like this: { path: Section.Security, canActivate: [AuthGuard, AccessGuard, AdminGuard], children: [ { path: '', pathMatch: 'full', ...

Tips for integrating an arrow function as a property in a functional programming approach using JavaScript or TypeScript

Suppose I were to create a constructor for a functional class with TypeA as an argument, and TypeB representing the type of the class itself. In such cases, I can implement it using: functionName(argument: TypeA): TypeB { this.property = argument; ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

Tips for determining the defaultValue type in React.context usage

'use client'; import { useState, createContext, useMemo } from 'react'; type MessageStatus = 'default' | 'success' | 'error'; export type MessageProps = { type: MessageStatus; payload: string; }; ty ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

Using Angular 2 to position a md-fab button with 'position: fixed' inside an inner component

Utilizing the md-fab-button from the initial angular2 material-framework has presented a challenge for me. I am attempting to set the md-fab-button(for adding a new entity) with position: fixed, but my goal is to position the button within an inner compone ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

What benefits does ngModel offer compared to input/event binding, template variable binding, and banana syntax for achieving two-way data binding?

When working on an Angular application, what benefits does the [(ngModel)] approach offer in achieving 2-way binding compared to three alternative methods? Additionally, which of these options are considered the best for implementing 2-way data binding, wh ...

Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format): [ { "name": "john", "lastName": "doe", "gender": "male" }, { "name": &qu ...

Error encountered within eot file using file-loader and webpack

I am facing an issue while trying to integrate React Rainbow Components with Next.js (TypeScript). I encountered a problem with importing fonts, which led me to use webpack along with the url-loader. However, despite my efforts, I keep encountering the er ...

Refresh the Angular component following updates to the store

Working with NGRX/Redux for the first time, I am puzzled by why my component fails to update after adding a new item to an array in the store. Within my main component, these properties are defined: productLines$: Observable<ProductionLine[]>; produ ...

Routes are not being registered by the TypeScript Express Restful API

After successfully creating a simple REST API for my Application using JavaScript, I decided to switch to TypeScript. I made some changes related to types and added a ts config file, and the Express-TypeScript server was up and running. However, when I tes ...