Search code examples
javascriptangularrouteshttpclientangular-router-guards

why I get this null message when trying to use my guard?


enter image description here

As you can see in the uploaded image, I have everything good imported as it should be when using httpClient, but i get this error when going to the route where I use my guard.

ERROR NullInjectorError: NullInjectorError: No provider for _HttpClient!
    at NullInjector.get (core.mjs:4674:27)
    at R3Injector.get (core.mjs:5117:33)
    at R3Injector.get (core.mjs:5117:33)
    at injectInjectorOnly (core.mjs:3831:40)
    at Module.ɵɵinject (core.mjs:3837:42)
    at Object.AuthService_Factory [as factory] (auth.service.ts:8:25)
    at core.mjs:5239:43
    at runInInjectorProfilerContext (core.mjs:3644:9)
    at R3Injector.hydrate (core.mjs:5238:17)
    at R3Injector.get (core.mjs:5106:33)

My guard:

import { CanMatchFn } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { inject } from '@angular/core';

export const authGuard: CanMatchFn = (route, segments) => {
  const authService = inject(AuthService);
  if(authService.auth.id){
    return true;
  }
  return false;
};

The route I use it

    {
        path: 'heroes',
        loadChildren: () => import('./heroes/heroes.module').then(m => m.HeroesModule),
        canMatch: [authGuard]
    },

If I erase canMatch: [authGuard], then works fine, and it should be, because I have been using httpClient in my project before and everything worked fine


Solution

  • The Error you are encountering is because the AuthService is injecting the HttpClient without a provider for it. I guess your AuthService is used as a singleton so you can just import the HttpClientModule inside the app.module.ts or if you are working in Angular 17+ you can provide it inside the appConfiguration via provideHttpClient().