What are Route Guards?
Route guards are interfaces (or functions) that tell the Angular Router whether it should allow navigation to a requested route. As an Architect, you use guards to enforce business rules at the navigation level. For example, your Revochamp 'Admin' panel should only be accessible to users with an 'Admin' role, and the 'Editor' should warn users if they try to leave with unsaved code.
- Types of Route Guards
Angular provides several types of guards, each triggered at a different point in the routing lifecycle.
- CanActivate: Determines if a user can visit a route (e.g., Is the user logged in?).
- CanActivateChild: Determines if a user can visit the child routes of a protected parent.
- CanDeactivate: Determines if a user can leave a route (e.g., 'Warning: Unsaved Changes').
- CanMatch: Determines if a route can be matched at all (useful for choosing between two different components for the same path based on a flag).
- Implementing Functional Guards
In modern Angular (v15+), functional guards are the preferred standard over class-based guards. They are easier to write, test, and compose using Dependency Injection.
- Registering Guards in Routes
You apply guards directly to your route configuration. You can provide an array of multiple guards; all must return true for navigation to proceed.
Guard Execution Flow
The router checks guards in a specific sequence before the component is even instantiated.
| Guard Type | Primary Use Case | Return Value |
|---|---|---|
| CanActivate | Authentication / Login check | boolean | UrlTree |
| CanDeactivate | Prevent accidental data loss | boolean | Promise<boolean> |
| CanMatch | Feature flagging / Role-based routing | boolean |
| CanActivateChild | Protecting sub-menus/dashboards | boolean |