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

Angular 12自定义库服务注入HttpClient时出现inject()调用上下文错误

问题原因

该错误是Angular依赖注入上下文无效导致的,常见触发原因有3种:

  1. 主应用根模块未导入HttpClientModule,公共库服务依赖的HttpClient没有对应注入提供商
  2. 本地调试时公共库和主应用加载了多份不同的@angular/core实例,注入器上下文不互通,通常出现在使用npm link关联本地公共库的场景
  3. 公共库打包时未将Angular相关依赖标记为对等依赖,把Angular核心代码打进了库产物中,和主应用的Angular实例产生冲突
修复方案

按以下步骤逐一排查修复:

  • 检查主应用根模块配置,确保导入HttpClientModule:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule // 必须添加该导入
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • 如果使用npm link本地调试公共库,在主应用的angular.json中配置路径重定向,强制所有Angular依赖使用主应用目录下的版本:
// angular.json 对应项目的build配置项
"architect": {
  "build": {
    "options": {
      "paths": {
        "@angular/*": ["./node_modules/@angular/*"]
      }
    }
  }
}
  • 检查公共库的package.json配置,将所有Angular相关依赖放在peerDependencies字段下,不要放在dependencies中:
{
  "peerDependencies": {
    "@angular/common": "^12.0.0",
    "@angular/core": "^12.0.0"
  }
}
  • 检查公共库的编译配置,在tsconfig.lib.json的angularCompilerOptions中开启部分编译模式,适配Ivy编译规则:
{
  "angularCompilerOptions": {
    "compilationMode": "partial",
    "enableIvy": true
  }
}

内容的提问来源于stack exchange,提问作者Eric Malalel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:24:00