Issue
My app-routing.module.ts contains parameter routes that lead to a distinct id. I found out that my wildcard path was broken while testing my routes.
After considerable testing, it turns out that using a different route below the parameter path also doesn't work.
app-routing.module.ts (original setup)
const routes: Routes = [
{
path: '',
pathMatch: 'full',
loadChildren: () =>
import('./features/home/home.module').then((m) => m.HomeModule),
},
{
path: 'about',
loadChildren: () =>
import('./features/about/about.module').then((m) => m.AboutModule),
},
{
path: 'contact',
loadChildren: () =>
import('./features/contact/contact.module').then((m) => m.ContactModule),
},
{
path: ':id',
loadChildren: () =>
import('./features/profile/profile.module').then(
(m) => m.ProfileModule
),
},
// PATH BELOW NOT WORKING 👇
{
path: '**',
redirectTo: '',
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
initialNavigation: 'enabledBlocking',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
app-routing.module.ts (testing by swapping some path setup)
const routes: Routes = [
{
path: '',
pathMatch: 'full',
loadChildren: () =>
import('./features/home/home.module').then((m) => m.HomeModule),
},
{
path: ':id',
loadChildren: () =>
import('./features/profile/profile.module').then(
(m) => m.ProfileModule
),
},
// PATH BELOW NOT WORKING 👇
{
path: 'about',
loadChildren: () =>
import('./features/about/about.module').then((m) => m.AboutModule),
},
{
path: 'contact',
loadChildren: () =>
import('./features/contact/contact.module').then((m) => m.ContactModule),
},
{
path: '**',
redirectTo: '',
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
initialNavigation: 'enabledBlocking',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
Solution
First of all, a redirectTo
route must contain a pathMatch
property, otherwise it will not route (it should not even compile)
Next, it's a bad practice to provide routes at the same level like so
/home/about
/home/contact
/home/:id
Technically, it works, but because it relies on the order of the provided routes. if your :id
route is set first in the list, then about
and contact
become ids too.
So the best solution would be to just separate the routes like so
/home/about
/home/contact
/home/items/:id
Otherwise, you can use the canMatch
guard (like canActivate
), but again, I would consider this a bad practice. Just follow a RESTFul-like structure for your routes, that's the best and simplest option.
Answered By - MGX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.