我使用 Angular Guard 来保护我的路由,我在主路由中添加canActivate attr 并且它工作正常,而对于子单路由(ReportsRouteModule/RequestsRouteModule ...),如果我想启用防护,我还需要在每个路由中设置 canActivate路线,我认为这是使用角度防护的不好方法并且浪费了很多时间。那么有什么方法可以避免它并在主路由中管理它。
请看我的应用结构和一些代码如下: 1. 应用结构:
|-- app.module.ts
|-- app-routing.module.ts(master route)
|-- app.component.ts
|-- report
|-- report-route.module.ts(sub route)
|-- report-aa
|-- report-bb
|-- report-cc
|-- request
|-- request-route.module.ts(sub route)
|-- request-aa
|-- request-bb
|-- request-cc
|-- etc.
- 代码:主路由
const routes: Routes = [
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
// providers: [AuthGuard]
})
export class AppRoutingModule {
子路线:
const routes: Routes = [
{
path: 'reports',
canActivateChild: [AuthGuard],
children: [
{path: '', redirectTo: 'reports', pathMatch: 'full'},
{path: 'A', component: AReportsComponent},
{path: 'B', component: BReportsComponent},
{path: 'C', component: CReportsComponent},
]
}
];
@NgModule({
imports: [
RouterModule.forChild(routes),
],
declarations: [
AReportsComponent,
BReportsComponent,
CReportsComponent,
]
})
export class ReportsRouteModule {
}