问题描述
有关 Route Guards 的angular2文档离开了我不清楚何时将CanActivate
防护与CanActivateChild
防护与无组件路由结合使用是合适的.
The angular2 documentation about Route Guards left me unclear about when it is appropriate to use a CanActivate
guards vs. a CanActivateChild
guard in combination with component-less routes.
TL; DR:当我可以在canActivate
中使用无组件的路由来达到相同的效果时,具有canActivateChild
有什么意义?
TL;DR: what's the point in having canActivateChild
when I can use a component-less routes with canActivate
to achieve the same effect?
长版:
我发现CanActivateChild
在底部被选中,而CanActivate
在顶部被选中.对我来说没有意义的是文档中给出的以下示例:
I get that CanActivateChild
is checked bottom up and CanActivate
is checked top down. What doesn't make sense to me is the following example given in the docs:
@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
路径具有一个无组件的路由:
So the admin
path has a component-less route:
在这种情况下,为什么代码会将AuthGuard
插入到子级和根组件中(路径admin
)?根源就够了吗?
Why is the code in this case inserting the AuthGuard
in the child and in the root component (path admin
)? Wouldn't is suffice to guard at the root?
我基于删除canActivateChild: [AuthGuard]
并添加注销按钮的示例创建了 plunkr 在AdminDashboard
上.果然,父路由的canActivate
仍然保持警惕,那么当我可以在canActivate
中使用无组件路由时,具有canActivateChild
有什么意义呢?
I have created a plunkr based on the sample that removes the canActivateChild: [AuthGuard]
and adds a logout button on the AdminDashboard
. Sure enough, the canActivate
of the parent route still guards, so what's the point in having canActivateChild
when I can use component-less routes with canActivate
?
推荐答案
这是一个实际的例子:
- 导航到
/admin
-
canActivate
已选中 - 您可以在
/admin
路线的子级之间导航,但不会调用canActivate
,因为它可以保护/admin
每当在其定义的路由的子级之间进行更改时,都会调用 -
canActivateChild
.
- navigating to
/admin
canActivate
is checked- You navigate between the children of
/admin
route, butcanActivate
isn't called because it protects/admin
canActivateChild
is called whenever changing between children of the route its defined on.
我希望这可以帮助您(如果仍然不清楚的话),可以通过添加调试它们的防护措施来检查特定功能.
I hope this helps you, if still unclear, you can check specific functionality by adding guards debugging them.
这篇关于CanActivate与CanActivateChild使用无组件路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!