Interesting in your question is the wording:
Is there a way to say: "Go to this route if the canActivate class evaluates to false "
And as you expressed the βintuitiveβ solution:
{ path: 'log-in', component: LoginComponent, canActivate: [ !UserLoggedInGuard ] },
Which basically says you need to negate result UserLoggedInGuard@canActivate
Consider the following implementation of UserLoggedInGuard :
@Injectable() export class UserLoggedInGuard implements CanActivate { constructor(private _authService: AuthService) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return this._authService.isLoggedIn(); } }
Next, consider the solution proposed by @Mike
@Injectable() export class NegateUserLoggedInGuard implements CanActivate { constructor(private _authService: AuthService) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return !this._authService.isLoggedIn(); } }
The approach is now approved, but closely related to the (internal) implementation of UserLoggedInGuard . If, for some reason, the implementation of UserLoggedInGuard@canActivate changes, NegateUserLoggedInGuard will break.
How can we avoid this? Simple abuse addiction injection:
@Injectable() export class NegateUserLoggedInGuard implements CanActivate { constructor(private _userLoggedInGuard: UserLoggedInGuard) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return !this._userLoggedInGuard.canActivate(route,state); } }
Now it does exactly what you expressed with
canActivate: [ !UserLoggedInGuard ]
And the best part:
- It is not closely related to the internal implementation of
UserLoggedInGuard - Can be extended to manage the result of more than one
Guard class