Search code examples
javascriptangularangular-routing

Angular child page refresh redirects to root


The problem regards routing in an Angular 13 app which is divided in few components. Components hierarchy is something like this:

  • User (root)
    • Child 1
      • Child 1-1
    • Child 2

The root component is under the /u url so it's renderized when you go to localhost:4200/u. Its html contains a simple menubar which has buttons that redirects to child components (all of them works correctly, no problems at all) and contains a router-outlet so that they can be renderized internally. The problem comes when I'm, for example, on Child 1-1 and I refresh the page. What happens is that Angular routes to /u/child-1/child1-1 but soon after it routes to /u. This issue also doesn't make possible for me to access the app directly from /u/child-1/child-1-1 which is a big problem because I need it.

Routes are configured correctly (otherwise routing from /u to its children wouldn't work correctly which does) but I'll report them just in case:

user.route.ts:

const children: Routes = [
  child1Route,
  child2Route,
];

export const USER_ROUTE: Route = {
  path: 'u',
  component: UserComponent,
  data: {
    pageTitle: 'user.title'
  },
  canActivate: [AuthGuard], //disabled
  children: children
};

export const USER_ROUTES: Routes = [USER_ROUTE];
child1.route.ts

const children: Routes = [
  child1-1Route
];

export const child1Route: Route = {
  path: 'child1',
  component: ChildOneComponent,
  children: children
}
child1.route.ts

export const child1-1Route: Route = {
  path: 'child1-1',
  component: ChildOneOneComponent,
}

USER_ROUTE is then inserted into RouterModule.forRoot(USER_ROUTE) in user.module.ts (but again, is not our concern because if roots were bad configured it wouldn't have worked at all). I didn't report child2 routes because they are useless for this purpose.

Has anyone ever experienced something like this? How can I understand what is going on?

The only thing I tried succesfully was to listen for url changes in user.component.ts and redirect to /u/child-1/child-1-1 whenever someone went to /u but as you can imagine this is very dirty because I can't use /u anymore if I do it like this.


Solution

  • It seems like a bug which can happen in some Angular versions with some specific dependencies (I guess..). I'll leave here the bug request from GitHub just in case it gets updated and someone has my same problem.

    https://github.com/angular/angular/issues/26905