Angular – NullInjectorError No provider for HttpClient
Issue Description
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,
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. Please follow the below steps to resolve the issue.
Please register HttpClientModule in the root NgModule. File location app.module.ts
Configure for Application project – no provider for HTTP client
Add import statement as below,
import { HttpClientModule } from '@angular/common/http';
Also please update the @NgModule decorator within the import section as below in the same file,
imports: [ BrowserModule, AppRoutingModule, HttpClientModule ],
Example:
Configure for Test project – no provider for HTTP client
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 below,
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
Then please add the HttpClientTestingModule to the TestBed.
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
Example:
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
References:
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.