Search code examples
angularangular-router-guardsangular17

Angular 17 - functional guard - ERROR NullInjectorError: NullInjectorError: No provider for


I am migrating old angular project to latest angular 17. I changed class based auth guard to functional auth guard. The problem I am having is that I get this error:

ERROR NullInjectorError: NullInjectorError: No provider for _UserService!
at NullInjector.get (core.mjs:5626:27)
at R3Injector.get (core.mjs:6069:33)
at R3Injector.get (core.mjs:6069:33)
at injectInjectorOnly (core.mjs:911:40)
at ɵɵinject (core.mjs:917:42)
at inject (core.mjs:1001:12)
at authGuard (auth.guard.ts:6:23)
at router.mjs:3323:134
at runInInjectionContext (core.mjs:6366:16)
at router.mjs:3323:89

Here is my authGuard code:

import {CanActivateFn, Router} from '@angular/router';
import {inject} from "@angular/core";
import {UserService} from "../users/user.service";

export const authGuard: CanActivateFn = (route, state) => {
  const userService = inject(UserService);
  const router = inject(Router);

  if (!userService.is_authenticated()) {
    router.navigate(['login', state.url]);
    return false;
  }
  return true;
};

Here is part of my UserService:

import {Injectable} from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class UserService {
    private usersUrl = '/users/';

    constructor(private http: HttpClient,
                private jwtHelper: JwtHelperService) { }

    ...

    public is_authenticated(): boolean {
        const token = localStorage.getItem('token');
        // Check whether the token is expired and return
        // true or false
        return !this.jwtHelper.isTokenExpired(token);
    }
}

As I understand the documentation I don't need to provide UserService anywhere. Using 'inject' should be enough. What am I doing wrong?


Solution

  • The solution was adding this to providers in app.config.ts:

    export const appConfig: ApplicationConfig = {
      providers: [
        UserService, JwtHelperService, { provide: JWT_OPTIONS, useValue: JWT_OPTIONS },
       ...
    ]