Route Guards
Level: Intermediate
ℹ️ What You'll Learn
- CanActivate guard (protect routes)
- Auth guard (require login)
- CanDeactivate (unsaved changes)
- Guard implementation
- Route protection patterns
Auth Guard
import { Injectable } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class authGuard implements CanActivateFn {
constructor(private auth: AuthService, private router: Router) {}
canActivate() {
if (this.auth.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Or functional guard:
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) {
return true;
} else {
router.navigate(['/login']);
return false;
}
};
Using Guards in Routes
export const routes: Routes = [
{ path: 'login', component: LoginComponent },
{
path: 'students',
component: StudentListComponent,
canActivate: [authGuard]
},
{
path: 'students/:id/edit',
component: StudentFormComponent,
canActivate: [authGuard]
}
];
Protected routes require guard to pass.
Admin Guard
export const adminGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isAdmin()) {
return true;
} else {
alert('Admin access required');
router.navigate(['/students']);
return false;
}
};
// Routes
{
path: 'settings',
component: SettingsComponent,
canActivate: [adminGuard]
}
CanDeactivate (Unsaved Changes)
export const unsavedChangesGuard: CanDeactivateFn<any> = (component, route, state) => {
if (component.form && component.form.dirty) {
return confirm('You have unsaved changes. Leave anyway?');
}
return true;
};
// Routes
{
path: 'students/:id/edit',
component: StudentFormComponent,
canDeactivate: [unsavedChangesGuard]
}
Data Guard (Check Resource Exists)
export const studentGuard: CanActivateFn = (route, state) => {
const id = route.paramMap.get('id');
const studentService = inject(StudentService);
const router = inject(Router);
return studentService.getStudent(+id!).pipe(
map(() => true),
catchError(() => {
router.navigate(['/students']);
return of(false);
})
);
};
Verify resource exists before loading.
SMS Guards Example
// Auth guard
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.getToken()) {
return true;
}
router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
};
// Teacher guard (only teachers can manage exams)
export const teacherGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.getUserRole() === 'teacher';
};
// Routes
export const routes: Routes = [
{ path: 'login', component: LoginComponent },
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [authGuard]
},
{
path: 'exams',
component: ExamListComponent,
canActivate: [authGuard, teacherGuard]
},
{
path: 'students/:id/edit',
component: StudentFormComponent,
canActivate: [authGuard],
canDeactivate: [unsavedChangesGuard]
}
];
Key Takeaways
- CanActivate guard = protect routes
- Guard checks before navigation
- Return true = allow, false = block
- Multiple guards = all must pass
- Auth guard = common pattern
- CanDeactivate = warn before leaving
💡 Backend Developer Tip
Guards similar to Authorization middleware in ASP.NET. Check permissions before serving resource.
⚠️ Guard Issues
- Guard doesn't redirect — Route loads anyway
- Not checking token expiry — Allow expired tokens
- Redirect loop — Guard redirects to protected route
- Multiple guards conflict — Order matters
🤖Use AI to Learn Faster
Use ChatGPT, Claude, or Copilot to go deeper on Route Guards. Try these prompts:
"Why use guards instead of checking in component?""How do you handle expired tokens?""When use multiple guards?""Quiz me on route guards"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.
nexcoding.in
Have questions on your tech stack, ongoing projects, or need one-to-one training?