Reputation: 746
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
Upvotes: 4
Views: 3120
Reputation: 3724
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
Upvotes: 6