Performance: Route guards (canActivate, canDeactivate)
Route guards affect the initial navigation speed and responsiveness when changing routes in an Angular app.
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> { // Async non-blocking permission check const result = await this.permissionService.checkPermissionsAsync(); return result; }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// Synchronous heavy computation or blocking call
const result = this.heavyPermissionCheck();
return result;
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy guard | 0 (no DOM changes yet) | 0 | Blocks paint until done | [X] Bad |
| Asynchronous guard with Promise | 0 | 0 | Non-blocking paint | [OK] Good |
canActivate guard in Angular routing?canActivatecanActivate is a route guard that runs before entering a route to decide if navigation is allowed.canDeactivate checks leaving a route, not entering. Preloading and error handling are unrelated to canActivate.canDeactivate guard to a route in Angular?canDeactivate is used to check if navigation away from a route is allowed.canDeactivatecanDeactivate: [GuardName] inside the route object.canDeactivate guard code snippet, what will happen when the user tries to leave the EditComponent with unsaved changes?export class UnsavedChangesGuard implements CanDeactivate<EditComponent> {
canDeactivate(component: EditComponent): boolean {
if (component.hasUnsavedChanges()) {
return confirm('You have unsaved changes. Leave anyway?');
}
return true;
}
}component.hasUnsavedChanges() returns true, then asks for confirmation.confirm() returns true allowing navigation; otherwise, navigation is blocked.canActivate guard implementation:export class AuthGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isLoggedIn()) {
return true;
}
}
}isLoggedIn() is false, the method returns nothing (undefined), which is invalid.canActivate must return true, false, or an observable/promise resolving to those. Missing return causes errors.canDeactivate to achieve this?canDeactivate runs when leaving a route, so it is the correct place to check and confirm navigation.Pass the test and this pattern moves unknown