Search code examples
angularangular-servicesangular-standalone-components

NullInjectorError - Root standalone component does not import HttpClientModule properly


I have an issue, I want to rewrite my app code and change main module to main root standalone component pointed in main.ts.

All works fine but I have an issue with HttpClientModule. I am using HttpClient in one of services which is provided in root. In MainComponent i added HttpClientModules to imports array but then error occurs which is saying I didn't provided HttpClientMoudle to app and this service can't use it.

Uncaught (in promise): NullInjectorError: R3InjectorError(Standalone[MainComponent])[MainService -> MainService -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!

When I added this HttpClientModule to AppRoutingModule which I also added to main.ts as

bootstrapApplication(MainComponent, {
  providers: [importProvidersFrom(RoutingModule)],
});

it works fine, service has no any problem.

Here is a code with basic example of this problem, could someone explain me why import to root standalone component doesn't work in this case but import to RoutngModule is solves the problem?

https://stackblitz.com/edit/angular-fhpbvm?file=src/main.ts


Solution

  • Problem solved. In this case, I have to add provideHttpClient()to providers array in bootstrapApplication() function in main.ts file.

    import { provideHttpClient } from "@angular/common/http";
    
    bootstrapApplication(AppComponent, {
      providers: [
        importProvidersFrom(AppRoutingModule),
        provideHttpClient()
      ]
    })