我是一个新的Angular用户
在我的案例中,我想在一些路径中使用guard。
Shell.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>
app-routing.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
. 我怎样才能做到这一点?
首先,你需要修改你的 AuthenticationGuard
从 CanActivateChild
到 CanActivate
第二,去除 canActivateChild: [AuthenticationGuard]
从 Shell.ts
三、如果您需要使用认证上 module1
,你只需要添加 canActivate: [AuthenticationGuard]
到 app-routing.module.ts
像这样。
{ path: 'module1', loadChildren: () =>
import('./module1/module1.module').then(m => m.module1), canActivate: [AuthenticationGuard] },
在可以激活检查像:-
allowedModules = ['module2','module3']
filteredModule = allowedModules.find((module)=>state.url.includes(module));
return !!filteredModule;