Member-only story
Route Guards in Angular
Guarding routes in Angular is a fundamental concept for securing and controlling access to specific routes within your application. Angular provides a powerful mechanism to protect routes using guards. Guards can be used to implement authentication, authorization, and other route protection mechanisms. In this explanation, I’ll provide a detailed overview of route guards in Angular with examples.
There are four types of route guards in Angular:
- CanActivate:
- This guard determines whether a route can be activated. It’s commonly used for authentication and authorization checks before navigating to a route.
Example: Let’s create a simple AuthGuard
to protect a route. Suppose you want to protect an admin panel route:
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, 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 | UrlTree {
if (this.authService.isLoggedIn()) {
return true;
} else {
// Redirect to the login page if not logged in
return this.router.parseUrl('/login');
}
}
}
In this example, the AuthGuard
checks if the user is logged in using the AuthService
. If…