6

目前,在 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
}, {

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

4

2 回答 2

3

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

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
    }
于 2018-02-09T22:30:29.387 回答
3

我个人认为,如果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
  }
];
于 2018-09-10T04:35:39.587 回答