To fix NullInjectorError: No provider for HttpClient! error in Angular follow the below steps.
- Open
app.module.ts
file of Angular Application. - Import
HttpClientModule
from@angular/common/http
. - Add
HttpClientModule
to 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
.spec
file. - import
HttpClientTestingModule
from ‘@angular/common/http/testing’ - Add
HttpClientTestingModule
to 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();
}));
});