Home > other >  Redirect empty route when using an empty route with children
Redirect empty route when using an empty route with children

Time:12-02

When the route is blank (i.e. https://localhost:1234) I want it to route to the search component.

I have routing set up in my app.module.ts like this:

RouterModule.forRoot([
      { path: '', redirectTo: 'search', pathMatch: 'full' },
      { path: 'login', component: LoginComponent },
      {
        path: '', component: BasicLayoutComponent,
        children: [
          { path: 'search', component: SearchComponent },
          { path: 'settings', component: SettingsComponent },
          { path: 'profile', component: ProfileComponent }
        ]
      },
      { path: '**', redirectTo: 'search' }
    ]),

This isn't working however, when I go to an empty route it is loading the BasicLayoutComponent without loading any of the child paths/components.

I have also tried putting the redirect route in the children like so:

RouterModule.forRoot([
      { path: 'login', component: LoginComponent },
      {
        path: '', component: BasicLayoutComponent,
        children: [
          { path: '', redirectTo: 'search', pathMatch: 'full' },
          { path: 'search', component: SearchComponent },
          { path: 'settings', component: SettingsComponent },
          { path: 'profile', component: ProfileComponent }
        ]
      },
      { path: '**', redirectTo: 'search' }
    ]),

This also doesn't work and has the same problem (routes to empty BasicLayoutComponent). I've even tried having it in both places with no luck.

The wildcard redirect works correctly, navigating to /test for example redirects to /search.

What am I doing wrong?

This is with angular packages ^14.0.3.

CodePudding user response:

It seems having { path: '', redirectTo: 'search', pathMatch: 'full' }, as the first entry was correct.

My issue was caused by an imported module that had routing set up like this:

RouterModule.forRoot([
      {
        path: '', component: BasicLayoutComponent, children: [
          { path: 'users', component: UsersIndexComponent }
        ]
      }
    ])

I changed it to this and now my default redirect is working correctly:

RouterModule.forRoot([
      {
        path: 'users', component: BasicLayoutComponent, children: [
          { path: '', component: UsersIndexComponent }
        ]
      }
    ])

CodePudding user response:

Here is a solution

App Routes

const routes: Routes = [
  {path: '', redirectTo: '/auth/sign-in', pathMatch: 'full'}
];

Auth Routes (as example)

const routes: Routes = [
  {
    path: 'auth',
    component: AuthComponent,
    children: [
      {path: 'sign-in', component: SignInComponent}
    ]
  },

];
  • Related