Search code examples
angularangular17

Using AuthGuard For Angular 17 routes


I am following the docs of angular from Angular Guard

Below is my Guest Guard Code. The logic is to check if the user is available or not,

if available, redirect to dashboard else proceed to login page.

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


@Injectable()

class PermissionsService {
  canActivate(): boolean {
    return false;
  }

}

export const guestGuard: CanActivateFn =  (route, state) => {
  return inject(PermissionsService).canActivate();
};

But this code throws error as

[ERROR] TS2304: Cannot find name 'inject'. [plugin angular-compiler]

src/app/guards/guest.guard.ts:15:13:
  15 │       return inject(PermissionsService).canActivate();

Solution

  • You need to import inject() from @angular/core.