I'm working with Nested Module Structure and having some difficulty to implement guard.
Right Now I have to use canActivate
on parent module route and canActivateChild
on every child module route.
I want a solution where I will just put guard on Parent module route and that guard will also be activated on all the child module routes...
Following is the module structure
app-routing.module.ts
{
path: 'pages',
loadChildren: () => PagesModule,
},
pages-routing.module.ts canActivate
on AdminModule
route.
{
path: 'admin',
loadChildren: () => AdminModule,
canActivate: [AuthGuard],
},
admin-routing.module.ts canActivateChild
on every child module of admin
{
path: 'dashboard',
loadChildren: () => DashboardModule,
canActivateChild: [AuthGuard],
},
{
path: 'allusers',
loadChildren: () => AllUsersModule,
canActivateChild: [AuthGuard],
},
dashboard-routing.module.ts
const routes: Routes = [{ path: '', component: DashboardComponent }];
allusers-routing.module.ts
const routes: Routes = [{ path: '', component: AllUsersComponent }];
AuthGaurd
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(
private readonly authService: AuthService,
private readonly route: Router,
) {}
async canActivate() {
if (this.authService.isLoggedOut()) {
localStorage.clear();
this.route.navigate(['/login']);
alert('Access Denied Token Not Found');
return false;
} else {
return true;
}
}
canActivateChild(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| boolean
| UrlTree
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree> {
return this.canActivate();
}
}