5
votes

I have an issue with a component lazy loaded and a parameter. I have two modules : a dashboard module (DashboardModule) with a dashboard component (DashboardComponent) and another module called user (UserModule) with one component (UserComponent) for the example. The UserComponent is used to display one user or create a new user. I want to lazy load the module UserModule. So my configuration in my file app.routing.ts is :

export const appRoutes: Routes =  [
    { path: '',   redirectTo: '/dashboard', pathMatch: 'full' },
    { path: '**', redirectTo: '/dashboard', pathMatch: 'full' },
    { path: 'user', loadChildren: 'app/user/user.module#UserModule' },
]

@NgModule({
  imports: [ RouterModule.forRoot(appRoutes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

Now, in my module User, I have a file to configure my routes : user.routing.ts. And I want to have the same route for my two cases : display one user if there is an id in my route or create a user if the id is empty. So I try this but it is not working :

const userRoutes: Routes = [
    { path: '', component: UserComponent },
    { path: ':id', component: UserComponent } // This line does not work
];

@NgModule({
    imports: [RouterModule.forChild(userRoutes)],
    exports: [RouterModule]
})
export class UserRoutingModule { }

If I had an Id to my route, it is not work and automaticaly the route goes back to User. For example : locahost:4200/user/123 does not work and there is a redirection to localhost:4200/user

I don't find sample with this case so I hope someone will help me.

Thank you.

2
When I have seen this happen is when there is an error somewhere. Have you checked the console to see if any errors are occurring? You could also consider turning on route tracing (as shown here stackoverflow.com/questions/43618663/…) to better see what is happening.DeborahK
Are you importing UserRoutingModule in user.module?Gauss
@adrien did you ever find an answer?crh225
same action here with Angular 9. the scenario is implemented here, but it works!! stackblitz.com/edit/angular-ivy-rfjphdHamed Zakery Miab
Are you using angular along side another server-side framework like MVC? and Are you using useHash: true in your real-world code?Hamed Zakery Miab

2 Answers

0
votes

The order of the routes matter. The router will try and match the route from top to bottom. The '**' route will match anything, hence the router will match dashboard before the intended user route

-1
votes

You should remove

{ path: '**', redirectTo: '/dashboard', pathMatch: 'full' },

setting from appRoutes