angular – No provider for HttpClient
angular – No provider for HttpClient
To resolve this problem HttpClient
is Angulars mechanism for communicating with a remote server over HTTP.
To make HttpClient
available everywhere in the app,
- open the root
AppModule
, - import the
HttpClientModule
from@angular/common/http
,import { HttpClientModule } from @angular/common/http;
- add it to the
@NgModule.imports
array.imports:[HttpClientModule, ]
You have not provided providers in your module:
<strike>import { HttpModule } from @angular/http;</strike>
import { HttpClientModule, HttpClient } from @angular/common/http;
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule
],
providers: [ HttpClientModule, ... ]
// ...
})
export class MyModule { /* ... */ }
Using HttpClient in Tests
You will need to add the HttpClientTestingModule
to the TestBed configuration when running ng test
and getting the No provider for HttpClient error:
// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from @angular/common/http/testing;
// Other imports
import { TestBed } from @angular/core/testing;
import { HttpClient, HttpErrorResponse } from @angular/common/http;
describe(HttpClient testing, () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
// Inject the http service and test controller for each test
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
it(works, () => {
});
});
angular – No provider for HttpClient
You are getting error for HttpClient so, you are missing HttpClientModule for that.
You should import it in app.module.ts file like this –
import { HttpClientModule } from @angular/common/http;
and mention it in the NgModule Decorator like this –
@NgModule({
...
imports:[ HttpClientModule ]
...
})
If this even doesnt work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.