首页 > 解决方案 > 仅在 childRoutes 上使用 CanActive 制作角度

问题描述

我是 Angular 的新手

就我而言,我想在某些路径中使用警卫

壳牌.ts

export class Shell {
   static childRoutes(routes: Routes): Route {
       return {
           path: '',
           component: ShellComponent, // Component that have a navbar
           children: routes,
           canActivateChild: [AuthenticationGuard],
       };
   }
}

shell.component.html

// some code html of navbar here
<router-outlet></router-outlet>

应用程序路由.module.ts

const routes: Routes = [
   Shell.childRoutes([
      { path: 'module1', loadChildren: () => import('./module1/module1.module').then(m => m.module1) },
      { path: 'module2', loadChildren: () => import('./module2/module2.module').then(m => m.module2) },
      { path: 'module3', loadChildren: () => import('./module3/module3.module').then(m => m.module3) },
   ]),
];

我只想将 canActivateChild 用于module3. 我该怎么做?

标签: angular

解决方案


首先,你需要修改你的AuthenticationGuardfromCanActivateChildCanActivate

二、canActivateChild: [AuthenticationGuard]Shell.ts

第三,如果你需要使用身份验证module1,你只需要canActivate: [AuthenticationGuard]app-routing.module.ts这样添加:

{ path: 'module1', loadChildren: () => 
  import('./module1/module1.module').then(m => m.module1), canActivate: [AuthenticationGuard] },

推荐阅读