Sunday 13 February 2022

Angular – NullInjectorError No provider for HttpClient

 Angular runtime gives error-nullinjectorerror: no provider for httpclient!

ERROR NullInjectorError: R3InjectorError(AppModule)[AccountService -> HttpClient -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
at NullInjector.get (http://localhost:4200/vendor.js:11077:27)
at R3Injector.get (http://localhost:4200/vendor.js:25117:33)

In Chrome or other browser,

nullinjectorerror: no provider for httpclient!

Resolution

The issue is more due to not registering the required services i.e HttpClientModule in the root module ie. NgModule.

As per Angular Design and Architecture every service (internal or external service) is required to be registered with root NgModule as required.

This issue could exist in the Application and in the Unit Test project also. Please follow the below steps to resolve the issue.

Please register HttpClientModule in the root NgModule. File location app.module.ts

Add import statement as below,

 
import { HttpClientModule } from '@angular/common/http'; 

Also please update @NgModule decorator within the import section as below in the same file,

  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],

Example:

nullinjectorerror: no provider for httpclient!

Configure for Test project error- no provider for httpclient

While writing the Unit test for HttpClient dependent services you may find it is very useful to use HttpClientTestingModule.

This module is very helpful for testing especially Data services that make HTTP calls to the Servers. Please import the HttpClientTestingModule and the mocking controller, HttpTestingController, along with the other symbols your tests require.

Please add below import statement,

1
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';

Then please add the HttpClientTestingModule to the TestBed.

1
2
3
4
beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [ HttpClientTestingModule ]
    });

Example:

nullinjectorerror: no provider for

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

No comments:

Post a Comment