Type of guards in Angular
There are several types of guards in Angular, each serving a different purpose in controlling access to routes and data in your application. Here are some of the most common types of guards with examples:
CanActivate
: This guard is used to control access to a route. It returns a boolean value indicating whether or not the route can be activated. For example, you could use aCanActivate
guard to restrict access to a route if the user is not authenticated:
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;
}
}
}
CanActivateChild
: This guard is used to control access to child routes of a parent route. It works similarly to theCanActivate
guard, but for child routes. For example, you could use aCanActivateChild
guard to restrict access to a parent route and all of its child routes if the user is not authorized:
import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivateChild {
constructor(private authService: AuthService, private router: Router) {}
canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (this.authService.isAuthorized()) {
return true;
} else {
this.router.navigate(['/unauthorized']);
return false;
}
}
}
CanDeactivate
: This guard is used to control access when navigating away from a route. It returns a boolean value or aPromise
or anObservable
that resolves to a boolean value indicating whether or not the navigation can be completed. For example, you could use aCanDeactivate
guard to confirm with the user before navigating away from an unsaved form:
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { FormComponent } from './form.component';
@Injectable({
providedIn: 'root'
})
export class FormGuard implements CanDeactivate<FormComponent> {
canDeactivate(component: FormComponent) {
if (component.form.dirty) {
return confirm('Are you sure you want to leave this form?');
}
return true;
}
}