Search code examples
angulartypescriptangular2-routing

Incorrect functioning of routes in Angular


When trying to navigate from 'users' to 'users/:id' like this

this.router.navigate([`/users/${userId}`]);

or

this.router.navigate(['/users', userId]);

it stays on 'users' but url in browser bar changes to 'users/{correct_id}'

Application structure:

  • dashboard (/)
  • login (/login)
  • users (/users)
    • users/id (/users:id)

I suspect the problem lies in my routes but unfortunately I can't find it.

app-routing.module.ts:

const routes: Routes = [
{
    path: '',
    component: DashboardComponent,
    loadChildren: (): Promise<DashboardModule> =>
        import('./dashboard/dashboard.module').then(
            (m: typeof import('./dashboard/dashboard.module')): DashboardModule => m.DashboardModule
        )
},
{
    path: 'login',
    component: LoginComponent,
    loadChildren: (): Promise<LoginModule> =>
        import('./login/login.module').then(
            (m: typeof import('./login/login.module')): LoginModule => m.LoginModule
        )
},
{
    path: 'users',
    component: UsersComponent,
    loadChildren: (): Promise<LoginModule> =>
        import('./users/users.module').then(
            (m: typeof import('./users/users.module')): UsersModule => m.UsersModule
        )
},
{
    path: '**',
    redirectTo: ''
}

];

users-routing.module.ts:

const routes: Routes = [
{
    path: '',
    component: UsersComponent,
},
{
    path: ':id',
    component: UserProfileComponent,
},

];


Solution

  • The problem is probably in the following route:

    {
      path: 'users',
      component: UsersComponent, // <-- HERE
      loadChildren: (): Promise<LoginModule> =>
        import('./users/users.module').then(
          (m: typeof import('./users/users.module')): UsersModule => m.UsersModule)
    },
    

    When you assign a component to a route, when that route matches, this component will always get rendered. And if it has children, they will get rendered in the <router-outlet> of that UserComponent template.

    Since you also have the UserComponent assign to the children root path, I guess that's not the case.

    To solve it you just need to remove the component line from the 'users' route.

    {
      path: 'users',
      loadChildren: (): Promise<LoginModule> =>
        import('./users/users.module').then(
          (m: typeof import('./users/users.module')): UsersModule => m.UsersModule)
    },
    

    Cheers