Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 397
Alaksandar Jesus Gene Avatar asked Mar 04 '26 22:03

Alaksandar Jesus Gene


1 Answers

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

like image 50
Matthieu Riegler Avatar answered Mar 07 '26 17:03

Matthieu Riegler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!