简体   繁体   中英

canActivateChild and redirectTo

Here's my app.routing.ts

export const appRoutes: Routes = [
  {
    path: '',
    canActivate: [MyAuthGuard],
    canActivateChild: [MyAuthGuard],
    children: [
      {
        path: '',
        redirectTo: '/my-default-page',
        pathMatch: 'full'
      },
      {
        path: 'some-feature',
        redirectTo: '/some-route-defined-in-other-module'
      }
    ]
  },
  { path: '404', component: NotFoundComponent },
  { path: '**', redirectTo: '/404' }
];

If I navigate to localhost:4200/some-feature I can see MyAuthGuard.canActivateChild is not called, however if I change the app.routing.ts to

export const appRoutes: Routes = [
      {
        path: '',
        canActivate: [MyAuthGuard],
        canActivateChild: [MyAuthGuard],
        children: [
          {
            path: '',
            redirectTo: '/my-default-page',
            pathMatch: 'full'
          },
          {
            path: 'some-feature',
            component: MyComponent
          }
        ]
      },
      { path: '404', component: NotFoundComponent },
      { path: '**', redirectTo: '/404' }
    ];

and navigate to localhost:4200/some-feature I can now see MyAuthGuard.canActivateChild is called.

My question is, why is MyAuthGuard.canActivateChild not called when the child is a redirection ?

As far as I know, it's not possible to redirect to a route in another module directly. The right way to do this is by loading the module in the AppRoutingModule like this:

{
  path: 'redirect-feature',
  loadChildren: './other/other.module#OtherModule'
},

As part of the OtherModule you define separate routes for the components in the OtherRoutingModule :

const routes: Routes = [
  {
    path: '',
    redirectTo: 'feature',
  },
  {
    path: 'feature',
    component: FeatureComponent,
  }
];

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

Then the guards should work as expected. The redirects for this module are configured in the OtherRoutingModule , too. You also have the option to add guards to the routes in OtherRoutingModule , depending on what you need.

I also created an example in StackBlitz .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM