【问题标题】:Apply router guard to all children except one将路由器保护应用于除一个之外的所有孩子
【发布时间】:2018-07-20 18:22:29
【问题描述】:

目前,在 Angular 中,您可以通过对其中一个父路由应用路由器保护来限制对所有子路由的访问:

export const routes: Routes = [
  {
    path: 'my-account',
    canActivate: [IsUserLoggedIn],
    children: [{
      path: 'settings',
      component: SettingsComponent
    }, {
      path: 'edit-profile',
      component; EditProfileComponent
    }]
  }
];

这对于避免在每条路由中重复 canActivate 保护很有用。但是现在当我想在my-account 下引入第三条应该可以公开访问的路由时会发生什么?例如,my-account/help 可能有一个可公开访问的帮助页面,每个人都应该能够访问,即使他们没有登录:

}, {
  path: 'help',
  component: HelpComponent,
  // Somehow make exception to canActivate guard above
}, {

是否有一种干净的方法可以做到这一点,或者是唯一的方法来破坏路由的组织并手动将路由器保护应用于每个子路由,帮助页面除外?

【问题讨论】:

    标签: angular angular-router angular-router-guards


    【解决方案1】:

    我个人认为如果HelpComponent 路由不需要保护,它需要在不同的父路由中。所以,这是组织路线的问题。

    但是,无论如何,您也可以为它创建一个单独的路由,例如:

    export const routes: Routes = [
      {
        path: 'my-account',
        canActivate: [IsUserLoggedIn],
        children: [{
          path: 'settings',
          component: SettingsComponent
        }, {
          path: 'edit-profile',
          component: EditProfileComponent
        }]
      },
      {
        path: 'my-account/help',
        component: HelpComponent
      }
    ];
    

    【讨论】:

      【解决方案2】:

      我能想到的唯一解决方案是:

      canActivate(
              next: ActivatedRouteSnapshot,
              state: RouterStateSnapshot): boolean {
      
             // In the next you have .url prop so you can check for it 
             if (state.url.indexOf('help') !== -1) { return true; }
      
             // Your current Guard logic
          }
      

      【讨论】:

      • 是的,我也想过,但似乎组织不力。我觉得应该在路由中处理逻辑。
      • 好吧,Guard 应该保护 root 和 children 路由,所以如果应该保护哪些子路由有异常,那么 guard 是添加此类异常的完美位置。其他解决方案是在没有保护的情况下向公共父级提供帮助(肯定会丢失所需的路由嵌套)。
      猜你喜欢
      • 2019-04-23
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2017-03-19
      • 2017-08-25
      • 2019-04-19
      相关资源
      最近更新 更多