Functional Guards in Angular

368 views Asked by At

I want to prevent navigation by changing the URL and only navigate on button click. My code:

import {Injectable} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class CanActivateGuard {
  private allowNavigation = false;

  constructor(private router: Router) {}

  setAllowNavigation(allow: boolean) {
    this.allowNavigation = allow;
  }

  canActivate: CanActivateFn = (): boolean => {
    if (this.allowNavigation) {
      return true;
    } else {
      this.router.navigate(['']); // Redirect to a safe route if not allowed
      return false;
    }
  };
}

Is this correct for functional guard in angular? I'm still writing a class, so I think I'm doing something wrong here. The setAllowNavigation is called from clicking a button.

I was expecting to have only one function where I can pass a parameter to allow navigation or not and this parameter would be a default parameter to false.

1

There are 1 answers

0
Matthieu Riegler On

When defining a fonctionnal guard like CanActivateFn you should be having only a function:

For example :

const canActivateTeam: CanActivateFn =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
      return inject(PermissionsService).canActivate(inject(UserToken), route.params.id);
    };

This example is for the official doc.

If you need to injection something in that function you should rely on inject