Reputation: 54741
I'm working on an Angular 5 application that doesn't have a root /
route. It should redirect to one of the lazy loaded children. Each child module has its own redirect from /child
to /child/view
(where the word "child" is the name of the feature).
The idea is that the root routes don't know where the default route is for a child. So I can just redirect to the preferred child module, and let that child handle the final redirect. So there should be two redirects.
Here is my root MainRoutes.ts
file:
const routes: Routes = [
{path: '', redirectTo: '/posts', pathMatch: 'full'},
{
path: '', component: MainComponent,
children: [
{path: 'albums', loadChildren: 'app/Albums/Albums#AlbumsModule'},
{path: 'todos', loadChildren: 'app/Todos/Todos#TodosModule'},
{path: 'posts', loadChildren: 'app/Posts/Posts#PostsModule'},
{path: 'users', loadChildren: 'app/Users/Users#UsersModule'}
]
},
{path: '**', component: NotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class MainRoutesModule {
}
My main routes above should redirect the /
root path to the /posts
child route, but it's redirecting to /albums
instead. I can't tell if the problem is in my main routes definitions or my child routes.
Here is my AlbumsRoutes.ts
:
const routes: Routes = [
{path: '', redirectTo: '/albums/view', pathMatch: 'full'},
{path: 'view', component: ViewComponent}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AlbumsRoutesModule {
}
I also have TodosModule
, PostsModule
and UsersModule
which are the same as above (except with different names).
I wrote the above that way because I think the forChild
routes are relative to where they are loaded.
When I go to /
the URL is redirect to /albums/view
. It seems like the redirect defined in my root isn't being used. I need it to redirect to /posts/view
.
The fact that it goes to /albums/view
tells me that the routes for the first child are being used.
I know I've made a simple mistake, but I can't see it.
Upvotes: 1
Views: 3396
Reputation: 1110
I think redirectTo only works for routes on the same level.
You may try this instead
const routes: Routes = [
{path: '', redirectTo: '/posts', pathMatch: 'full'},
{
path: 'albums',
component: MainComponent,
loadChildren: 'app/Albums/Albums#AlbumsModule'
},
{
path: 'posts',
component: MainComponent,
loadChildren: 'app/Posts/Posts#PostsModule'
},
...
{path: '**', component: NotFoundComponent}
];
Upvotes: 2