What if your app could stop users from making mistakes before they happen, all by itself?
Why Route guards (canActivate, canDeactivate) in Angular? - Purpose & Use Cases
Imagine building a website where users can visit many pages, but some pages should only be seen if they are logged in or have special permission. You try to check these rules manually every time someone clicks a link or tries to leave a page.
Manually checking access on every page is tiring and easy to forget. Users might sneak into pages they shouldn't see, or lose their work if they leave a form without warning. This makes your app unreliable and frustrating.
Route guards like canActivate and canDeactivate automatically check if a user can enter or leave a page. They keep your app safe and user-friendly by stopping unwanted access or warning about unsaved changes.
if (!user.isLoggedIn) { alert('Access denied'); redirectToLogin(); }
canActivate() { if (user.isLoggedIn) { return true; } else { redirectToLogin(); return false; } }Route guards let you control navigation smoothly and securely, improving user experience and protecting sensitive pages effortlessly.
Think of an online shopping site where you must log in to see your cart (canActivate) and get a warning if you try to leave the checkout page without finishing (canDeactivate).
Manual checks for page access are error-prone and hard to maintain.
Route guards automate permission checks before entering or leaving pages.
This keeps apps secure and users informed about unsaved changes.
Practice
canActivate guard in Angular routing?Solution
Step 1: Understand the role of
canActivatecanActivateis a route guard that runs before entering a route to decide if navigation is allowed.Step 2: Differentiate from other guards
canDeactivatechecks leaving a route, not entering. Preloading and error handling are unrelated tocanActivate.Final Answer:
To check if navigation to a route is allowed before entering it. -> Option BQuick Check:
canActivate = check before entering route [OK]
- Confusing canActivate with canDeactivate
- Thinking canActivate preloads data
- Assuming canActivate handles errors
canDeactivate guard to a route in Angular?Solution
Step 1: Identify the guard type for leaving routes
canDeactivateis used to check if navigation away from a route is allowed.Step 2: Match syntax with
The correct syntax usescanDeactivatecanDeactivate: [GuardName]inside the route object.Final Answer:
{ path: 'edit', component: EditComponent, canDeactivate: [UnsavedChangesGuard] } -> Option AQuick Check:
canDeactivate syntax = canDeactivate: [Guard] [OK]
- Using canActivate instead of canDeactivate for leaving routes
- Confusing canLoad with canDeactivate
- Missing brackets around guard name
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;
}
}Solution
Step 1: Analyze the guard logic
The guard checks ifcomponent.hasUnsavedChanges()returns true, then asks for confirmation.Step 2: Understand the confirm behavior
If the user confirms,confirm()returns true allowing navigation; otherwise, navigation is blocked.Final Answer:
The user is asked to confirm leaving only if there are unsaved changes. -> Option DQuick Check:
canDeactivate confirms only if unsaved changes exist [OK]
- Assuming user can leave without confirmation always
- Thinking guard blocks leaving without prompt
- Believing confirm causes errors in Angular guards
canActivate guard implementation:export class AuthGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isLoggedIn()) {
return true;
}
}
}Solution
Step 1: Check all code paths return a value
IfisLoggedIn()is false, the method returns nothing (undefined), which is invalid.Step 2: Understand guard return requirements
canActivatemust return true, false, or an observable/promise resolving to those. Missing return causes errors.Final Answer:
Missing return statement when user is not logged in. -> Option AQuick Check:
All canActivate paths must return true/false [OK]
- Not returning false or redirect when unauthorized
- Confusing canActivate with canDeactivate method names
- Thinking services can't be used in guards
canDeactivate to achieve this?Solution
Step 1: Identify when to block navigation away
Blocking leaving only applies when editing and unsaved changes exist, so guard must check both conditions.Step 2: Use canDeactivate guard properly
canDeactivateruns when leaving a route, so it is the correct place to check and confirm navigation.Final Answer:
Use canDeactivate guard that checks component.isEditing and component.hasUnsavedChanges() before confirming navigation. -> Option CQuick Check:
canDeactivate with condition on editing and unsaved changes [OK]
- Using canActivate to block leaving routes
- Always returning true in canDeactivate guard
- Confusing canActivateChild with canDeactivate
Ready to prove it?
Pass the test and this pattern moves unknown
