Problem accessing RouterStateSnapshot on Angular function guards

108 Views Asked by At

Since the old method for Angular Guards (Class and injection token guards and resolvers) is deprecated (see angular deprecation docs) , I'm trying to update the usages of guards in my project. But I'm facing problems getting (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) in my guard function.

This is the old method:

Routing Module:

{
    path: 'Home',
    canActivate: [MyGuard],
    component: HomeComponent 
}

MyGuard:

import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class MyGuard implements CanActivate {

  constructor(private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean 
  {
    // logic goes here
  }
}

in new method, I get error on calling canActivate : Expected 2 arguments but git 0

New Method:

Routing Module:

{
    path: 'Home',
    canActivate: [() => inject(MyGuard).canActivate()],
    component: HomeComponent 
}

MyGuard:

import {ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class MyGuard {

  constructor(private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean 
  {
    // logic goes here
  }
}

1

There are 1 best solutions below

0
Ghonche Yqr On

I found the code snippet that describes the solution:

{
    path: 'Home',
    canActivate: [(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => inject(MyGuard).canActivate(next, state)],
    component: HomeComponent
}