Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canActivate guard works only after refresh

I have canActivate guard which is on all routes (on the parent route). It works correctly when I go to any link first time, but then, when I'm changing routes it does not work. Guard is about logged in users (If api returns that I am logged in I return true, else I redirect it to Sign in page) What I should do? Thanks

like image 734
Dato Gogshelidze Avatar asked Oct 21 '25 14:10

Dato Gogshelidze


1 Answers

In the same guard that you have defined, implement the CanActivateChild interface, and call the same logic. In your routes, define both the CanActivate, and the CanActivateChild.

In your guard

@Injectable()
export class MyGuard implements CanActivate, CanActivateChild {

  constructor() {}

  canActivate() {
    // Your logic here to identify the value to return
  }

  canActivateChild() {
     return this.canActivate();
  }
}

In your routing

let routes:Routes = [
 { 
   path: 'myPath', 
   canActivate: [ MyGuard ] 
   canActivateChild: [ MyGuard ],
   children: [
     { path: 'mychild1', .... },
     { path: 'mychild2', .... }
   ]
]

Read this guide on angular.io re protecting child routes : https://angular.io/guide/router#canactivatechild-guarding-child-routes

like image 127
JeanPaul A. Avatar answered Oct 23 '25 03:10

JeanPaul A.