Angular 15+ New Way of Functional Router Guards

🔸In Angular v14.2, angular team announced New Router API for standalone.

🔸Functional router guards in Angular allow you to define guards using functions instead of classes.

🔸This can be particularly useful when you want to keep your code concise and avoid creating separate guard classes. Here's how you can use functional router guards in Angular:

🔸Before Angular 15, We need to do Implement Guard with CanActivate and to do the logic inside the guard as class.

Angular 15 below.

   
  
  


@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authServices: AuthService, private router: Router, private alertify: AlertifyService) {}

  canActivate(): Observable | Promise | boolean {
    if (this.authServices.loggedIn()) {
      return true;
    }

    this.alertify.error('You need to be loggin to acces this area');
    this.router.navigate(['/home']);
    return false;
  }
}


Activate in guard

admin.guard.ts

In Angular 15+ , configure inline like below or more logic use it as function.

1️⃣ Inline: Here functional guards can still inject dependencies with inject from @angular/core :

   
  
const route = {
  path: ‘admin’,
  canActivate: [() => inject(AuthService).isLoggedIn()]
};

2️⃣ . you can use it as function like below .

   
    
    
    
    import { inject } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivateChildFn, CanActivateFn, Router, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "../service/auth.service";


// add the guard as function and configure it in the related routes 


export const AdminauthGuard: CanActivateFn = (
  route: ActivatedRouteSnapshot,

  state: RouterStateSnapshot
) => {
  const auth = inject(AuthService);
   const router = inject( Router)
  if(auth.login){
    console.log("true");
    alert('authentication allowed');
    return true
  }
  alert("Authentication retsricted");
  router.navigate(['/product']);
  return false;
};
    
    
    
    
    

Advantages of functional Guards.

✅ Functional route guards require just a single function, and can be written in a separate file, or created inline for a route if needed.

✅Functional router guards with inject() are lightweight, ergonomic, and more composable than class-based guards.

In this example , if we need to check simple logic , we need to write class based guards which implements canActivate.
   
  
  
  
  @Injectable({providedIn: 'root'})
  export class LoggedInGuard implements CanActivate {
    constructor(private loginService: LoginService) {}
    canActivate() {
      return this.loginService.isLoggedIn();
    }
  }
  const route = {
    path: 'admin',
    canActivate: [LoggedInGuard]
  };    

Comments