0

I want to use the canActivate guard in routing without repeating the

canActivate: [AuthGuard],

code like below

import { AuthGuard } from 'src/app/core/guards/auth.guard';
 
const routes: Routes = [{
  path: '', data: { title: 'Users' },
  children: [
    {
          path: 'createuser',
          canActivate: [AuthGuard],
          component: UserComponent,
          data: { title: 'Create User' }
        },
     {
          path: 'updateuser',
          canActivate: [AuthGuard],
          component: UpdateUserComponent,
          data: { title: 'Update User' }
        },
  ]
}];
Piumi ganegoda
  • 163
  • 3
  • 12

2 Answers2

0

In your example you can use canActivateChild

import { AuthGuard } from 'src/app/core/guards/auth.guard';
 
const routes: Routes = [{
  path: '', data: { title: 'Users' },
  canActivateChild: [AuthGuard],
  children: [
    {
          path: 'createuser',
          component: UserComponent,
          data: { title: 'Create User' }
        },
     {
          path: 'updateuser',
          component: UpdateUserComponent,
          data: { title: 'Update User' }
        },
  ]
}];

so this auth guard will be applied to all children

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
0

I think you're looking for CanActivateChild, it lets you specify a guard for all child routes

import { AuthGuard } from 'src/app/core/guards/auth.guard';
 
const routes: Routes = [{
  path: '', data: { title: 'Users' }, canActivateChild: [AuthGuard]
  children: [
    {
          path: 'createuser',
          component: UserComponent,
          data: { title: 'Create User' }
        },
     {
          path: 'updateuser',
          component: UpdateUserComponent,
          data: { title: 'Update User' }
        },
  ]
}];

Tooked from: https://angular.io/api/router/CanActivateChild

ntoniocp
  • 34
  • 2