2
2
2
Route guards in Angular are used to control and protect navigation to certain routes in your application.
They provide a way to implement security and access control, data preloading, and other navigation-
related logic. There are several types of route guards in Angular:
1. **CanActivate:**
- The `CanActivate` route guard determines whether a route can be activated. It's commonly used for
implementing authentication checks.
- Example use case: Only allow authenticated users to access the "Profile" route.
2. **CanActivateChild:**
- Similar to `CanActivate`, but it applies to child routes. It allows or denies access to child routes based
on certain conditions.
- Example use case: Ensure that a user can access the parent route and all its child routes only if they
meet specific criteria.
3. **CanDeactivate:**
- The `CanDeactivate` route guard is used to prevent users from leaving a route with unsaved changes
or data.
- Example use case: Display a confirmation dialog when a user tries to leave a form page with unsaved
changes.
4. **CanLoad:**
- The `CanLoad` route guard is used to prevent the lazy loading of feature modules unless specific
conditions are met.
- Example use case: Load the admin module only if the user is an admin.
5. **Resolve:**
- The `Resolve` route guard is used for data preloading. It allows you to fetch data before a route is
activated and ensure that the component receives the necessary data.
- Example use case: Load user data before displaying the "User Profile" page.
To implement route guards, you typically create services or classes that implement the corresponding
guard interfaces (e.g., `CanActivate`, `CanDeactivate`). These services/classes contain the logic for
checking conditions and returning `true` or `false` based on whether the route should be allowed.
```typescript
@Injectable({
providedIn: 'root',
})
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | UrlTree {
if (this.authService.isAuthenticated()) {
return true;
} else {
return this.router.createUrlTree(['/login']);
}
}
```
Then, you can apply this guard to a route in your route configuration:
```typescript
// Other routes...
];
```
By using route guards, you can enhance the security and user experience of your Angular application by
controlling access to routes, handling unsaved data, and preloading necessary data.