Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CanActivate AuthGuard Ignored?

I'm loading a books module with the following routing configuration (src/app/index.ts) -- Note that this is a stackblitz link - And it now works by implementing the fix in the answer - to break it remove the authguard from the Books Module routing:

{
  path: 'books',
  loadChildren: './books/books.module#BooksModule',
  canActivate: [AuthGuard],
},

The routing in the books module (src/app/books/index.ts) looks like this:

export const routes: Routes = [
  { path: '', component: CollectionPageComponent },
];

For some reason loading this route switches off the AuthGuard / the CanActivate guard does not trigger. There is a logging statement inside it tracking when it triggers.

If the route is commented out like this:

export const routes: Routes = [
//{ path: '', component: CollectionPageComponent },
];

Then the guard triggers. Thoughts?

like image 265
Ole Avatar asked Apr 10 '26 09:04

Ole


2 Answers

The problem is that the authguard needs to live inside your BooksModule route definition.

#in books/index.ts

export const routes: Routes = [
  { path: '', component: CollectionPageComponent, canActivate: [AuthGuard] },
];

you can then remove the canActivate from app/index.ts

like image 129
Mike Tung Avatar answered Apr 12 '26 23:04

Mike Tung


You can only use the canActivate guard with component. If you want guard on your lazy-loaded module, use canLoad guard.

like image 20
Sachin Gupta Avatar answered Apr 12 '26 22:04

Sachin Gupta