Angular 7 项注入服务正在取消设置
Angular 7 injected service being unset
我正在通过构造函数将服务简单地注入到我的组件中。在 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
。我的代码中没有任何内容可以直接设置注入对象的值。它怎么会变得不确定?
root提供详细服务
@Injectable({
providedIn: 'root'
})
export class DetailService {
我认为是因为this
上下文
而不是;
subscribe(this.updateHazardClassificationSingleton)
尝试;
subscribe(this.updateHazardClassificationSingleton.bind(this))
我正在通过构造函数将服务简单地注入到我的组件中。在 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
。我的代码中没有任何内容可以直接设置注入对象的值。它怎么会变得不确定?
root提供详细服务
@Injectable({
providedIn: 'root'
})
export class DetailService {
我认为是因为this
上下文
而不是;
subscribe(this.updateHazardClassificationSingleton)
尝试;
subscribe(this.updateHazardClassificationSingleton.bind(this))