Angular 5中使用ChangeDetectorRef出现注入错误的技术求助
你遇到的NullInjectorError: No provider for ChangeDetectorRef和StaticInjectorError,本质是Angular的依赖注入(DI)系统找不到ChangeDetectorRef的提供者,通常是组件配置或注入步骤出了问题。结合你的场景(PrintComponent中调用getqr更新打印视图),我给你梳理下具体的解决步骤:
1. 确保正确导入并注入ChangeDetectorRef
首先,在你的PrintComponent里,必须先从@angular/core导入ChangeDetectorRef,然后在构造函数中完成依赖注入——这里一定要加上访问修饰符(private或public),这样Angular的DI系统才能识别并提供这个服务:
// print.component.ts import { Component, ChangeDetectorRef } from '@angular/core'; // 其他必要的导入(比如你的API服务)... @Component({ selector: 'app-print', templateUrl: './print.component.html', styleUrls: ['./print.component.css'] }) export class PrintComponent { qrData: any; // 存储请求返回的二维码数据 // 正确注入ChangeDetectorRef constructor(private cdr: ChangeDetectorRef) { } getqr(selectedItemId: any) { // 发起网络请求获取选中条目的二维码数据 yourApiService.getQrCode(selectedItemId).subscribe((result) => { this.qrData = result; // 手动触发变更检测更新视图 this.cdr.detectChanges(); }); } }
2. 确认PrintComponent已在NgModule中注册
如果组件没有被添加到对应模块的declarations数组里,Angular的DI系统不会为它创建实例,自然找不到ChangeDetectorRef的提供者。打开你的AppModule(或对应功能模块),检查是否把PrintComponent加入了declarations:
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; // 如果用到网络请求需要导入 import { PrintComponent } from './print.component'; import { FirstComponent } from './first.component'; // 第一个触发选择的组件 // 其他导入... @NgModule({ declarations: [ PrintComponent, // 必须在这里注册 FirstComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [FirstComponent] }) export class AppModule { }
3. 避免在非组件类中注入ChangeDetectorRef
ChangeDetectorRef是组件级别的服务,只能在被@Component装饰的类中注入。如果你是在普通服务类里尝试使用它,那肯定会报错——这种情况可以考虑传递组件的ChangeDetectorRef实例到服务中,或者改用ApplicationRef来触发全局变更检测。
额外提示
如果你的组件是动态创建的,还需要确保在创建时把ChangeDetectorRef作为依赖传入,但从你的场景描述来看,应该是常规组件间调用,前面的步骤应该就能解决问题。
内容的提问来源于stack exchange,提问作者cfoster5

