angularangular-services

Why NullInjectionError problem not solved by adding ProvideHttpClient() in app.config file of Angular 18


I am trying to fetch data from the backend of my application. The data fetching works well with combination of promise and fetch function. But when I tried to implement it using HttpClient service it gives error. I checked previous response in this platform but couldn't solve the problem.

app.config.ts

import {ApplicationConfig} from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
  providers: [provideHttpClient()],
};

housing.service.ts

export class HousingService {
  url = "http://localhost:5150"
  protected homeLocationList2: HomeLocation[] = [];
  
  constructor(private http:HttpClient) { 
  }


  getAllProduct(): Observable<HomeLocation[]>{
    const response = this.http.get<HomeLocation[]>(`${this.url}/Home/AllProduct`)
    return response 
  }
}

Home.Component.ts

export class HomeComponent {
  productList:HomeLocation[] = [];
  housingService: HousingService = inject(HousingService)


  constructor(){
    this.housingService.getAllProduct().subscribe(data=>{
      this.productList = data;
    })
  }
}

This is the github link of the source code

https://github.com/ishanuzzal/angular_full_stack

Error I get

ERROR NullInjectorError: NullInjectorError: No provider for _HttpClient!
    at NullInjector.get (core.mjs:1632:21)
    at R3Injector.get (core.mjs:3014:27)
    at R3Injector.get (core.mjs:3014:27)
    at injectInjectorOnly (core.mjs:1095:36)
    at Module.ɵɵinject (core.mjs:1101:40)
    at Object.HousingService_Factory [as factory] (housing.service.ts:8:28)
    at core.mjs:3132:35
    at runInInjectorProfilerContext (core.mjs:866:5)
    at R3Injector.hydrate (core.mjs:3131:11)
    at R3Injector.get (core.mjs:3005:23)

Solution

  • It appears you have created an app.config.ts but you don't use it. Import it in src/main.ts:

    import { appConfig } from './app/app.config';
    
    bootstrapApplication(AppComponent, appConfig).catch((err) =>
      console.error(err),
    );
    

    Also make sure to add the config that you previously had in main.ts to app.config.ts:

    export const appConfig: ApplicationConfig = {
      providers: [
        provideHttpClient(),
        provideProtractorTestingSupport(),
        provideRouter(routeConfig),
      ],
    };