Route Guards protect routes from unauthorized access - like guards at castle gates.
1// guards/auth.guard.ts
2import { inject } from '@angular/core';
3import { Router, CanActivateFn } from '@angular/router';
4import { AuthService } from '../services/auth.service';
5
6export const authGuard: CanActivateFn = (route, state) => {
7 const authService = inject(AuthService);
8 const router = inject(Router);
9
10 if (authService.isLoggedIn()) {
11 return true;
12 }
13
14 // Redirect to login with saving the requested URL
15 return router.createUrlTree(['/login'], {
16 queryParams: { returnUrl: state.url }
17 });
18};1// guards/role.guard.ts
2export const roleGuard: CanActivateFn = (route, state) => {
3 const authService = inject(AuthService);
4 const requiredRole = route.data['role'] as string;
5
6 if (authService.hasRole(requiredRole)) {
7 return true;
8 }
9
10 return inject(Router).createUrlTree(['/forbidden']);
11};
12
13// Usage
14{
15 path: 'admin',
16 component: AdminComponent,
17 canActivate: [authGuard, roleGuard],
18 data: { role: 'admin' }
19}1export const unsavedChangesGuard: CanDeactivateFn<{ hasUnsavedChanges: () => boolean }> =
2 (component) => {
3 if (component.hasUnsavedChanges()) {
4 return confirm('You have unsaved changes. Are you sure you want to leave?');
5 }
6 return true;
7 };| Guard | When it executes | Use case | |-------|-----------------|----------| | CanActivate | Before entering a route | Authorization | | CanDeactivate | Before leaving a route | Unsaved changes | | CanLoad | Before lazy loading | Authorization for modules | | CanActivateChild | For child routes | Nested authorization | | Resolve | Before activation | Data fetching |