关于 Route Guards 的 angular2 文档让我不清楚何时适合使用 CanActivate
守卫与 CanActivateChild
守卫结合无组件路由。
TL;DR:当我可以使用带有 canActivate
的无组件路由来实现相同效果时,拥有 canActivateChild
有什么意义?
长版:
We can have multiple guards at every level of a routing hierarchy. The router checks the CanDeactivate and CanActivateChild guards first, from deepest child route to the top. Then it checks the CanActivate guards from the top down to the deepest child route.
我知道 CanActivateChild
是自下而上检查的,CanActivate
是自上而下检查的。对我来说没有意义的是文档中给出的以下示例:
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
canActivateChild: [AuthGuard],
children: [
{ path: 'crises', component: ManageCrisesComponent },
{ path: 'heroes', component: ManageHeroesComponent },
{ path: '', component: AdminDashboardComponent }
]
}
]
}
])
],
exports: [
RouterModule
]
})
export class AdminRoutingModule {}
所以 admin
路径有一个无组件路由:
Looking at our child route under the AdminComponent, we have a route with a path and a children property but it's not using a component. We haven't made a mistake in our configuration, because we can use a component-less route.
为什么在这种情况下,代码会在子组件和根组件(路径 admin
)中插入 AuthGuard
?守在根部还不够吗?
我创建了一个 plunkr基于删除 canActivateChild: [AuthGuard]
并在 AdminDashboard
上添加注销按钮的示例。果然,父路由的 canActivate
仍然是守卫,那么当我可以使用 canActivate
的无组件路由时,拥有 canActivateChild
有什么意义?
最佳答案
As we learned about guarding routes with CanActivate, we can also protect child routes with the CanActivateChild guard. The CanActivateChild guard works similarly to the CanActivate guard, but the difference is its run before each child route is activated. We protected our admin feature module from unauthorized access, but we could also protect child routes within our feature module.
这是一个实际的例子:
- 导航到
/admin
canActivate
已选中- 您在
/admin
路由的子级之间导航,但未调用canActivate
因为它保护/admin
canActivateChild
在其定义的路径的子节点之间发生变化时被调用。
我希望这对你有所帮助,如果仍然不清楚,你可以通过添加守卫调试它们来检查具体功能。
关于angular - 使用无组件路由的 CanActivate 与 CanActivateChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40163348/