Angular 19非独立项目中HttpClientModule标注已弃用问题排查
问题原因
在Angular 19中,HttpClientModule已被正式标记为废弃(deprecated),这就是你看到Core.Module中该模块标红并提示"The declaration was marked as deprecated here."的原因。
Angular从版本14开始逐步推广基于函数的提供者API,到19版本彻底弃用了HttpClientModule,转而使用provideHttpClient来配置HTTP客户端功能,包括拦截器。
修复方案
1. 移除CoreModule中的HttpClientModule导入
修改CoreModule代码,删除HttpClientModule的导入和在imports数组中的引用:
import { NgModule, Optional, SkipSelf } from '@angular/core'; import { CommonModule } from '@angular/common'; // 移除HttpClientModule的导入,保留HTTP_INTERCEPTORS import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { JwtInterceptor } from './interceptors/jwt.interceptor'; import { ErrorInterceptor } from './interceptors/error.interceptor'; import { LoadingInterceptor } from './interceptors/loading.interceptor'; @NgModule({ imports: [ CommonModule // 移除HttpClientModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true } ] }) export class CoreModule { constructor(@Optional() @SkipSelf() parentModule: CoreModule) { if (parentModule) { throw new Error('CoreModule is already loaded. Import it in the AppModule only.'); } } }
2. 在AppModule中配置provideHttpClient
修改AppModule,导入provideHttpClient和withInterceptorsFromDi(用于支持通过DI注入的拦截器),并添加到providers数组中:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; // 新增以下导入 import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { SharedModule } from './shared/shared.module'; import { BootstrapModule } from './shared/boostrap.module'; import { CoreModule } from './core/core.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, SharedModule, BootstrapModule, CoreModule ], providers: [ // 配置HTTP客户端,启用DI拦截器支持 provideHttpClient(withInterceptorsFromDi()) ], bootstrap: [AppComponent] }) export class AppModule { }
说明
provideHttpClient是Angular 19推荐的HTTP客户端配置方式,替代了原有的HttpClientModule。withInterceptorsFromDi选项用于兼容你现有通过HTTP_INTERCEPTORS令牌注册的拦截器,确保它们能正常工作。- 这种方式更符合Angular最新的依赖注入设计,也为后续迁移到独立组件架构做好准备。
内容的提问来源于stack exchange,提问作者Gbenga
相关产品推荐
相关产品推荐

