🚀 What are Route Guards?
- Route Guards are interfaces that allow you to control access to routes in your Angular application.
- They help protect routes by checking conditions before navigating to them.
📁 1. Create an AuthGuard
Suppose you want to create an AuthGuard to protect certain routes.
Generate the guard:
ng generate guard auth
Inside auth.guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
const isLoggedIn = this.authService.isLoggedIn();
if (!isLoggedIn) {
this.router.navigate(['/login']);
}
return isLoggedIn;
}
}
📄 2. Set Up Route Guard in App Routing
In app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{
path: 'protected',
canActivate: [AuthGuard],
loadChildren: () => import('./protected/protected.module').then(m => m.ProtectedModule)
},
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
✅ Key Point:
canActivateuses AuthGuard to protect the route.- The
ProtectedModulewill only load if the user is authenticated.
📦 3. Folder Structure Overview
/src
/app
/auth
auth.guard.ts
/protected
protected.module.ts
app-routing.module.ts
app.module.ts
🎯 Quick Tips
| Tip | Description |
|---|---|
| AuthGuard | Checks if the user is authenticated before accessing the route. |
| CanActivate | Used to protect routes by checking conditions. |
| CanDeactivate | Used to prevent navigation away from a route. |
| CanLoad | Used to prevent loading of lazy-loaded modules. |
⚡ Why Use Route Guards?
- Protect sensitive routes 🔒
- Ensure users meet certain conditions before accessing routes ✅
- Enhance security and user experience 🎯
Comments
Post a Comment