Angular 12自定义库服务注入HttpClient时出现inject()调用上下文错误
问题原因
该错误是Angular依赖注入上下文无效导致的,常见触发原因有3种:
- 主应用根模块未导入
HttpClientModule,公共库服务依赖的HttpClient没有对应注入提供商 - 本地调试时公共库和主应用加载了多份不同的@angular/core实例,注入器上下文不互通,通常出现在使用
npm link关联本地公共库的场景 - 公共库打包时未将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
相关产品推荐
相关产品推荐

