angular - 使用无组件路由的 CanActivate 与 CanActivateChild

标签 angular angular2-routing

关于 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 有什么意义?

最佳答案

From the docs:

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.

这是一个实际的例子:

  1. 导航到 /admin
  2. canActivate 已选中
  3. 您在 /admin 路由的子级之间导航,但未调用 canActivate 因为它保护 /admin
  4. canActivateChild 在其定义的路径的子节点之间发生变化时被调用。

我希望这对你有所帮助,如果仍然不清楚,你可以通过添加守卫调试它们来检查具体功能。

关于angular - 使用无组件路由的 CanActivate 与 CanActivateChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40163348/

相关文章:

angular - 在 Angular 2 中更改当前路由上的单个路由参数

Angular2 ComponentRouter 防止自动组件重用

Angular 2。检查访问后如何隐藏(不呈现)菜单中的链接?

angular - 将数据从子组件传递到父组件(子组件通过路由加载)

angular - 具有初始/之后状态的动画

javascript - 如何使用 Angular Materials 选项卡制作自定义选项卡?

angular - 在数据源更新时防止展开的 mat-table 折叠行(Angular Material)

Angular 2 CanActivate 不起作用

angular - AG-Grid:无法更新 Grid 中的字段,因为它是只读的

javascript - 从同一个弹出窗口运行两个 Angular 函数