Explain guards in Angular?
Guards in Angular are used to control access to routes in your application. They allow you to restrict access to certain parts of your application based on specific conditions. Guards are services that implement the CanActivate
interface, which defines a single method canActivate()
that returns a boolean value indicating whether or not the route can be activated.
Here’s an example of using a guard in Angular to restrict access to a route:
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 {
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
In this example, the AuthGuard
service implements the CanActivate
interface and the canActivate
method. The canActivate
method checks if the user is logged in by calling the isLoggedIn
method from the AuthService
. If the user is logged in, the method returns true
and the route is activated. If the user is not logged in, the method redirects the user to the login page and returns false
.
To use the guard, you need to add it to the canActivate
property of the route definition:
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
...
];
With this configuration, the AuthGuard
will be executed every time the user tries to navigate to the dashboard
route. If the guard returns false
, the user will be redirected to the login page and access to the dashboard
will be restricted.