Angular组件间用Service共享变量遇NullInjectorError报错修复
修复Angular服务注入的NullInjectorError错误
我正在学习通过Service在两个Angular组件之间共享变量,编写了以下代码:
共享数据服务(DataSharingService)
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataSharingService { private dataSource = new BehaviorSubject(false); data = this.dataSource.asObservable(); constructor() { } setData(data: boolean) { this.dataSource.next(data); } }
接收值的组件(Component1)
import { DataSharingService } from './data-sharing.service'; @Component({ // 组件专属配置 }) export class Component1 { data: boolean; constructor(private dataSharingService: DataSharingService) { this.dataSharingService.data.subscribe(data => this.data = data); } }
设置值的组件(Component2)
import { DataSharingService } from './data-sharing.service'; @Component({ // 组件专属配置 }) export class Component2 { constructor(private dataSharingService: DataSharingService) { } // 调用服务设置布尔变量值 someMethod() { this.dataSharingService.setData(true); } }
编译后Chrome控制台出现错误:ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[TestComponent -> TestService]
错误分析与修复方案
报错信息指向TestComponent依赖的TestService无法被注入,和你提供的DataSharingService代码无关,需要从以下几点排查:
- 检查TestService的注入配置:如果项目中存在
TestService,确保它添加了@Injectable({ providedIn: 'root' })装饰器,或者在对应的NgModule的providers数组中声明该服务。 - 核对组件依赖的服务名称:检查
TestComponent构造函数中注入的服务是否拼写正确,类名是否和实际服务类完全匹配。 - 确认模块导入关系:如果
TestService是在某个特定模块中提供的,确保该模块已经被导入到AppModule或者TestComponent所在的模块中。 - 清理缓存并重建项目:Angular的缓存可能导致依赖解析异常,执行
ng clean清除缓存后,再用ng serve重新启动项目。
内容的提问来源于stack exchange,提问作者Windows11
相关产品推荐
相关产品推荐

