未设置Angular 7注入服务

时间:2019-07-01 18:01:50

标签: angular dependency-injection angular7

我正在通过构造函数将服务简单地注入到我的组件中。在constructorngOnInit中,我都会打印出该值,并且我看到它是一个对象,正如预期的那样。在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 {

1 个答案:

答案 0 :(得分:0)

我认为这是因为this上下文

代替;

subscribe(this.updateHazardClassificationSingleton)

尝试;

subscribe(this.updateHazardClassificationSingleton.bind(this))