Angular 17 Router Guards: A Concise Guide
In Angular 17, router guards have evolved to provide a more concise and modern approach, leveraging functional programming introduced in Angular v14.2. These guards facilitate fine-grained control over navigation, authentication, data resolution, and lazy loading of modules. Let's explore the six different router guards available in Angular 17:
1. CanActivateFn
- Purpose: Determines if a route can be activated.
- Logic: Returns a boolean, UrlTree, or an Observable/Promise resolving to one of these.
true
: Navigation proceeds.false
: Navigation is blocked.UrlTree
: Redirection to a different route.
- Use Cases:
2. CanActivateChildFn
- Purpose: Identical to CanActivateFn, but specifically guards child routes of a given route.
- Use Cases:
- Protecting specific areas within a parent route based on additional criteria.
3. CanDeactivateFn
- Purpose: Decides if the user is allowed to navigate away from the current route.
- Logic: Returns a boolean, UrlTree, or an Observable/Promise resolving to one of these.
true
: Navigation proceeds.false
: Navigation is blocked.UrlTree
: Redirection to a different route.
- Use Cases:
- Displaying "are you sure?" type prompts for unsaved changes.
- Implementing custom logic for leaving a route (e.g., cleaning up resources).
4. CanMatchFn
- Purpose: Controls whether a route can even be matched, preventing the route from attempting to activate. Happens before CanActivate.
- Logic: Returns a boolean, or an Observable/Promise resolving to a boolean.
- Use Cases:
- Early redirection for unauthorized users
- Preventing lazy loading of modules based on certain conditions
5. ResolveFn
- Purpose: Fetches data before a route is activated.
- Logic: Returns data, an Observable/Promise resolving to data, or rejects with an error.
- Use Cases:
- Load necessary data required by the component before it renders.
- Ensure data is ready to avoid loading spinners or delayed renders.
6. CanLoadFn
- Purpose: Determines if a feature module can be lazy-loaded.
- Logic: Returns a boolean, UrlTree, or an Observable/Promise resolving to one of these.
- Use Cases:
- Role-based module loading (e.g., loading an Admin module only for admins)
- Prevent the loading of unused modules to optimize performance
Example Implementation (Authentication Guard)
import { Injectable } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivateFn {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
if (this.authService.isLoggedIn()) {
return true;
} else {
return this.router.createUrlTree(['/login']);
}
}
}
Routes Configuration:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
children: [
{ path: 'dashboard', component: DashboardComponent },
// Other child routes requiring authentication
]
},
{ path: 'login', component: LoginComponent },
// Other routes not requiring authentication
];
By leveraging these functional router guards, developers can implement robust navigation controls with ease and precision in Angular 17.
No comments:
Post a Comment