Route Guards are used to control access to routes (authentication, authorization).
typescript
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot): boolean {
if (this.authService.isLoggedIn()) {
return true; // Allow access
}
// Redirect to login
this.router.navigate(['/login']);
return false;
}
}
// app-routing.module.ts
const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard] // Protected route
},
{ path: 'login', component: LoginComponent }
];
// Other guards:
// canDeactivate - prevent leaving a page
// canLoad - prevent lazy loading
// canActivateChild - protect child routesYou should see
(If the user isn't logged in, they won't be able to access protected routes)