Route Guards & Resolvers
Route guards protect views from unauthorized access, while Resolvers prefetch server data before views are loaded.
1 Routing guards types
Angular provides specialized route guard interfaces:
- CanActivate: Checks if a user has permission to navigate to a route (e.g. validating auth tokens).
- CanDeactivate: Checks if a user can navigate away from a route (useful for warning users about unsaved form changes).
- Resolve: Fetches API data in the background before rendering a component, preventing partially loaded views.
2 Writing a CanActivate Guard
Let's check how an authentication guard is written in modern Angular:
TypeScript — Auth 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 {
const isLoggedIn = !!localStorage.getItem('token');
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
Apply this guard to your routing configurations array:
TypeScript — Guard Configuration
{
path: 'admin-dashboard',
component: AdminDashboardComponent,
canActivate: [AuthGuard]
}
3 Code Challenge
Challenge: Write a mock
Resolver service that simulates fetching database configurations (using of() with a 2-second delay) and binds it to a route path.