Problem Statement
Show how to protect a route so only authenticated users can access it.
Explanation
Implement CanActivate, check auth state, and return true/false, a UrlTree redirect, or an Observable/Promise of either.
Code Solution
SolutionRead Only
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean | UrlTree {
return this.auth.isLoggedIn() ? true : this.router.parseUrl('/login');
}
}
{ path: 'dashboard', canActivate: [AuthGuard], component: DashboardComponent }