Problem Statement
How do route guards protect Angular routes?
Explanation
Guards are services that implement interfaces like `CanActivate`, `CanDeactivate`, or `CanLoad`. They decide if a navigation is allowed. For auth, `CanActivate` checks token/session and either returns true or redirects to login. This centralizes access control.
Code Solution
SolutionRead Only
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.auth.isLoggedIn()) return true;
this.router.navigate(['/login']);
return false;
}
}