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:

  1. 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 a CanActivate 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;
    }
  }
}
  1. CanActivateChild: This guard is used to control access to child routes of a parent route. It works similarly to the CanActivate guard, but for child routes. For example, you could use a CanActivateChild 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;
    }
  }
}
  1. CanDeactivate: This guard is used to control access when navigating away from a route. It returns a boolean value or a Promise or an Observable that resolves to a boolean value indicating whether or not the navigation can be completed. For example, you could use a CanDeactivate 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;
  }
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *