Angular 2 Routing Lazy Loading - parameter in route

Viewed 1838

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 Answers

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

Related