本文介绍了CanActivate与CanActivateChild使用无组件路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关 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?

推荐答案

这是一个实际的例子:

  1. 导航到/admin
  2. canActivate已选中
  3. 您可以在/admin路线的子级之间导航,但不会调用canActivate,因为它可以保护/admin
  4. 每当在其定义的路由的子级之间进行更改时,都会调用
  5. canActivateChild.
  1. navigating to /admin
  2. canActivate is checked
  3. You navigate between the children of /admin route, but canActivate isn't called because it protects /admin
  4. 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使用无组件路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 11:27