我正在通过构造函数将服务简单地注入到我的组件中。在constructor
和ngOnInit
中,我都会打印出该值,并且我看到它是一个对象,正如预期的那样。在ngOnInit
中,我正在像这样进行valueChanges
订阅:
constructor(private readonly detailService: DetailService) {
}
ngOnInit(): void {
this.updateHazardClassificationSingleton();
this.thisTabFormGroup.valueChanges.pipe(
takeUntil(this.unsubscribe$)
).subscribe(this.updateHazardClassificationSingleton);
}
private updateHazardClassificationSingleton(): void {
this.detailService.setHazardClassification(this.hazardClassification);
this.detailService.setHazardClassificationIsSet(this.hazardClassificationIsSet);
}
手动运行updateHazardClassificationSingleton
方法时,注入的服务将在那里带有值。通过订阅运行时,注入的服务为undefined
。我的代码中没有任何东西可以直接设置注入对象的值。怎么会变得不确定?
详细服务在根目录中提供。
@Injectable({
providedIn: 'root'
})
export class DetailService {
答案 0 :(得分:0)
我认为这是因为this
上下文
代替;
subscribe(this.updateHazardClassificationSingleton)
尝试;
subscribe(this.updateHazardClassificationSingleton.bind(this))