Angular 9升级至15后出现NG0203注入上下文错误求助
问题详情
项目从Angular 9升级到15后,在Angular库的服务中注入HttpClient时出现NG0203错误,移除该注入后应用可正常运行。
涉及代码
- 库模块
app-lib.module.ts:
import { HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http'; providers: [ { provide: HTTP_INTERCEPTORS, useClass: HttpService, multi: true }, ],
- 服务
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 withEnvironmentInjector#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

