Problem Statement
What are Angular Guards and when would you use CanActivate vs CanLoad?
Explanation
Guards are services that decide if navigation is allowed. Use CanActivate to allow or block navigation to a route. Use CanLoad to prevent lazy modules from even being downloaded when the user is not authorized.
Code Solution
SolutionRead Only
export class AuthGuard implements CanActivate, CanLoad {
constructor(private auth: AuthService, private router: Router) {}
canActivate(){ return this.check(); }
canLoad(){ return this.check(); }
private check(){ if(this.auth.isLoggedIn()) return true; this.router.navigate(['/login']); return false; }
}Practice Sets
This question appears in the following practice sets: