如何检测属性何时更改服务?

时间:2017-08-02 03:25:49

标签: angular typescript

我希望组件能够订阅或通知服务中变量的更改。

我查看了Observables,但我认为这不会起作用,因为你需要完成流,我需要知道变量在整个组件处于活动状态时的变化。

有没有人知道这个好策略?

1 个答案:

答案 0 :(得分:5)

您是否尝试过Subject或其中的任何变体?

使用BehaviorSubject

的示例

服务:

export class MyService {
  myVariableSubject = new BehaviorSubject<number>(0);

  increase() {
    this.myVariableSubject.next(this.myVariableSubject.value + 1);
  }
}

组件:

constructor(private myService: MyService) {}

ngOnInit() {
  this.myService.myVariableSubject.subscribe((value: number) => console.log(value));
}

警告:这可能不是解决您问题的最合适的解决方案(您从未声明过)。

相关问题