Route Guards
Imagine a secure office building. You can't just walk into any room – you need a key card, and some rooms are restricted even with a key card. Route guards in Angular are like security guards that control access to certain routes based on conditions.
Angular provides several types of guards:
- CanActivate – Checks if a route can be accessed.
- CanActivateChild – Checks if child routes can be accessed.
- CanDeactivate – Checks if user can leave a route (e.g., unsaved changes).
- Resolve – Fetches data before route activates.
- CanLoad – Prevents lazy-loaded modules from loading.
Creating an Auth Guard (CanActivate)
Generate a guard using CLI:
ng generate guard auth
# or shorthand
ng g g auth
Choose CanActivate when prompted. Then implement the guard:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(): boolean {
// Check if user is logged in (example)
const isLoggedIn = localStorage.getItem('token') !== null;
if (!isLoggedIn) {
// Redirect to login page
this.router.navigate(['/login']);
return false;
}
return true;
}
}
Applying the Guard to Routes
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }
];
CanDeactivate Guard (Unsaved Changes)
This guard prevents users from accidentally leaving a form with unsaved changes.
export interface CanComponentDeactivate {
canDeactivate: () => boolean | Observable | Promise;
}
@Injectable({
providedIn: 'root'
})
export class UnsavedChangesGuard implements CanDeactivate {
canDeactivate(component: CanComponentDeactivate): boolean | Observable | Promise {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
Then in your form component, implement canDeactivate:
export class EditFormComponent implements CanComponentDeactivate {
formChanged = false;
canDeactivate(): boolean {
if (this.formChanged) {
return confirm('You have unsaved changes. Leave anyway?');
}
return true;
}
}
Two Minute Drill
- Route guards control access to routes.
- CanActivate checks if route can be entered.
- CanDeactivate checks if route can be left.
- Guards return boolean, Observable, or Promise.
- Apply guards in route configuration using canActivate, canDeactivate arrays.
Need more clarification?
Drop us an email at career@quipoinfotech.com
