Angular 18中HttpClientModule使用问题及配置位置咨询
Angular 18中provideHttpClient()的正确配置位置
直接把provideHttpClient()添加到app.config.ts的providers数组即可,无需在app.config.server.ts中重复配置。
原因
Angular 18的独立项目采用ApplicationConfig统一管理全局依赖:
app.config.ts是客户端与服务端共用的基础配置文件app.config.server.ts通过mergeApplicationConfig方法合并了app.config.ts的所有配置,基础配置中的提供者会自动同步到服务端配置中
修改后的app.config.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() // 新增这一行 ] };
关于之前的错误说明
HttpClientModule在Angular独立组件项目中已废弃,无法通过组件imports数组导入HttpClient是服务类,不属于组件、指令、管道或NgModule范畴,因此不能放入组件的imports数组,必须通过provideHttpClient()在全局提供者中注册后,才能在组件中通过依赖注入使用
内容的提问来源于stack exchange,提问作者Christian López
相关产品推荐
相关产品推荐

