Problem Statement
How do you protect routes so only logged-in users can access them?
Explanation
Use a `CanActivate` guard. The guard checks auth state; if allowed, it returns `true`. If not, it redirects to `/login` and returns `false`. Combine with an HTTP interceptor to attach tokens and with route data to manage roles.
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;
}
}