I have a project I migrated to Angular 18 with a setup to use the HttpClient
by importing the HttpClientModule
.
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
...
],
declarations: [
AppComponent,
...
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
In v17 HttpClientModule
everything was fine but now it is marked as deprecated.
Why is it deprecated and what is the replacement ?
The HttpClientModule
was superseeded by the already existing provideHttpClient()
provider function.
@NgModule({
imports: [
BrowserModule,
// Remove the module
...
],
declarations: [
AppComponent,
...
],
providers: [provideHttpClient()] // add it here
bootstrap: [ AppComponent ]
})
export class AppModule {}
If you were importing it in a component, it’s exactly the same change, remove the import and add provideHttpClient()
to the providers entry in the @Component({})
decorator.
The reason behind this change is that the HttpClientModule
doubled-up the provideHttpClient()
function that was introduced for standalone apps.
And here is an extract of the Angular source code, the module was really just providing the HttpClient. (No declarations, imports or export whatsoever)
@NgModule({
providers: [provideHttpClient(withInterceptorsFromDi())],
})
export class HttpClientModule {}
So the team chose to deprecate it and the deprecation message suggests to use the provideHttpClient()
provider function. This way devs would less be inclined to have both the module and the provider declared. Which was a common issue amongst new developers.