这是我的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' }
];
如果我导航到localhost:4200 / some-feature,我可以看到未调用MyAuthGuard.canActivateChild,但是如果我将app.routing.ts更改为
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' }
];
并导航到localhost:4200 / some-feature,现在我可以看到MyAuthGuard.canActivateChild被调用了。
我的问题是,当孩子是重定向对象时,为什么不调用MyAuthGuard.canActivateChild?
答案 0 :(得分:0)
据我所知,不可能直接重定向到另一个模块中的路由。正确的方法是像这样在AppRoutingModule
中加载模块:
{
path: 'redirect-feature',
loadChildren: './other/other.module#OtherModule'
},
在OtherModule
中,您为OtherRoutingModule
中的组件定义了单独的路由:
const routes: Routes = [
{
path: '',
redirectTo: 'feature',
},
{
path: 'feature',
component: FeatureComponent,
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class OtherRoutingModule { }
然后,警卫应按预期工作。此模块的重定向也已在OtherRoutingModule
中配置。您还可以根据需要选择向OtherRoutingModule
中的路由添加保护。
我还创建了一个example in StackBlitz。