I'm doing a project in Angular 18, I want to use the httpClientModule
but it tells me that it is deprecated when I want to import it directly into a component. Likewise, when I want to import the httpClient
within the imports of the same component it tells me component imports must be standalone components, directives, pipes, or must be NgModules.
I was investigating and it said that the solution is to put the provideHttpClient()
function within the providers of the app.module.ts
file but in my case I don't have that file, I only have the app.config.ts
and app.config.server.ts
In which of both should I put it?
The content of both files are this:
//app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes, withComponentInputBinding()), provideClientHydration()]
};
//app.config.server.ts
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
import { provideHttpClient } from '@angular/common/http';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering(),
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
The contents of app.config.ts
are also in app.server.ts
through mergeApplicationConfig
so you need to add provideHttpClient on app.config.ts
alone.
The contents of app.config.ts
go into bootstrapApplication
in main.ts
//app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes, withComponentInputBinding()),
provideClientHydration(),
provideHttpClient(), // <- changed here!
]
};