Reputation: 743
I use Angular Guard to protect my routes, i add canActivate attr in master route and it works fine, while for sub single routes(ReportsRouteModule/RequestsRouteModule...), if i want to enable guard, i alse need to set canActivate in each routes, i think it's a bad way to use angular guard and waste a lot time. So is there any way to avoid it and manage it in the master route.
Please see my application structure and some code as below: 1. app structure:
|-- 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 {
sub route:
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 {
}
Upvotes: 2
Views: 7220
Reputation: 4945
You can place the routes inside a parent route and use the canActive
on the parent route only. This way, the guard will match all child routes as well.
Sample code
{
path: "",
canActivate: [ParentAuthGaurdService],
children: [
{ path: "admin-dashboard", component: AdminDashboardComponent },
{ path: "admin/user", component: UserCrudComponent },
{ path: "admin/product", component: ProductCrudComponent }
]
}
Upvotes: 4
Reputation: 783
Some info on router internals, that will help you understand why adding canACtivateGuards
to each of the sub-module's root route is not a bad practice.
When you use Router
's forRoot
and forChild
, it merges the sub-modules routes
to parent module routes
array. So these routes becomes sibling routes. This means, you have to add canActivate
guard to each of the sub-module's top route.
If you do not want to do that, you have to mention all the other sub-routes as children to one parent route in app-routing as mentioned in the below answer(which is probably might not be what you are looking for).
Upvotes: 0