0

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
  }
}
Ghonche Yqr
  • 305
  • 1
  • 10

1 Answers1

0

I found the code snippet that describes the solution:

{
    path: 'Home',
    canActivate: [(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => inject(MyGuard).canActivate(next, state)],
    component: HomeComponent
}
Ghonche Yqr
  • 305
  • 1
  • 10