How to fix No provider for HttpClient error in Angular
To fix NullInjectorError: No provider for HttpClient! error in Angular follow the below steps.
- Open
app.module.tsfile of Angular Application. - Import
HttpClientModulefrom@angular/common/http. - Add
HttpClientModuleto the @NgModule imports array.
HttpClient is Angular’s way of communicating with a remote server over HTTP.
Ideally your AppModule class should be like this below.
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
As explained in my previous article EXCEPTION: No Provider For Http!
HttpClientModule introduced in version 4.3 of Angular.
The full stack trace of error will be
Error: StaticInjectorError[HttpClient]: StaticInjectorError[HttpClient]: NullInjectorError: No provider for HttpClient!
Most probably people will get the above error if they are upgrading their Angular application to the latest versions.
And people might forgot to add one of the above steps, like adding HttpClientModule to the @NgModule imports array.
Fixing No provider for HttpClient! error while running tests
And you might get this error while running your tests.
Then you should add HttpClientModule to your imports array of TestBed.configureTestingModule
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [FlexSearchService]
});
or If you are mocking the data, Then follow the below steps.
- Open your
.specfile. - import
HttpClientTestingModulefrom ‘@angular/common/http/testing’ - Add
HttpClientTestingModuleto the imports array of TestBed.configureTestingModule`
So your final .spec file should be like this.
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
HttpClientTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
});