Angular Component: No provider provider for HttpClient!

When attempting to utilize the HttpClient module in an Angular component or service but it has not been correctly imported and configured in the application’s module, the error message “No provider for HttpClient!” usually appears.

You must import the HttpClientModule from the @angular/common/http package and add it to the imports array in your application’s module file, which is often called app.module.ts, in order to resolve this error.
An illustration of how to import and set up the HttpClientModule in your app.module.ts file is given below:

If you are getting the following error while running ng test:

NullInjectorError: No provider for HttpClient!

the solution is to import HttpClientTestingModule in your spec file of your component


  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports:[HttpClientTestingModule]
    }).compileComponents();

The complete file will look like this:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';

import { YourComponent } from './YourComponent.component';

describe('YourComponent', () => {
  let component: YourComponent;
  let fixture: ComponentFixture<YourComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports:[HttpClientTestingModule],
      declarations:[....YourDeclarationsIfNeeded]
    }).compileComponents();

    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Please verify that you have followed these instructions and that you have imported HttpClient’s right route. It should be @angular/common/http.

Additionally, make sure that Angular and all of its dependencies are installed and current.