You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 9升级至15后出现NG0203注入上下文错误求助

Angular 9升级至15后注入HttpClient触发NG0203错误的解决办法

问题详情

项目从Angular 9升级到15后,在Angular库的服务中注入HttpClient时出现NG0203错误,移除该注入后应用可正常运行。

涉及代码

  1. 库模块 app-lib.module.ts:
import { HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpService,
      multi: true
    }, ],
  1. 服务 hero.service.ts:
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HeroService {
  texting: string = 'Wow!';
  constructor(private http: HttpClient) { }

  getResult() {
    return 'Wow!!!!!!';
  }
}

报错内容

Error: Uncaught (in promise): Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext.
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext.

解决步骤

  • 确认库模块的HttpClientModule导入:确保你的Angular库模块的imports数组中明确包含HttpClientModule,不要仅在主应用模块中导入。库作为独立单元,需要自行管理所需的模块依赖。

  • 调整服务的提供范围:providedIn: 'root'在库场景下可能引发注入上下文冲突。尝试移除该配置,改为在库模块的providers数组中声明服务:
    修改hero.service.ts:

    @Injectable()
    export class HeroService {
      texting: string = 'Wow!';
      constructor(private http: HttpClient) { }
    
      getResult() {
        return 'Wow!!!!!!';
      }
    }
    

    然后在app-lib.module.ts的providers中添加HeroService。

  • 排查拦截器的合法性:检查HttpService拦截器的构造函数是否正确注入依赖,是否符合Angular 15的注入规范。同时确认拦截器仅在库模块中注册一次,避免多模块重复注册导致的冲突。

  • 清理依赖缓存:升级后可能存在旧缓存干扰,执行以下命令重置依赖:

    rm -rf node_modules package-lock.json
    npm install
    
  • 检查库的构建配置:在库的ng-package.json中,将@angular/common/http添加到allowedNonPeerDependencies或声明为peerDependencies,避免依赖重复加载引发的上下文问题。

内容的提问来源于stack exchange,提问作者karthick ravindranath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:03:31