Angular 2从服务订阅布尔值

Bea*_*341 3 angular

我有一个具有变化的布尔值的服务,我想订阅组件中的布尔值变化。如何才能实现这一目标?

这是我的服务...

private subBoolShowHideSource = new Subject<boolean>();

subBoolShowHide$ = this.subBoolShowHideSource.asObservable();


showHide(eventValue: boolean) {
  this.subBoolShowHideSource.next(eventValue);
  console.log("show hide service " + eventValue);
}
Run Code Online (Sandbox Code Playgroud)

这是我试图读取布尔值的组件......

boolShowGTMDetails: any;
subscription: Subscription;

constructor(private service: ShowHideService){
  this.subscription = this.service.subBoolShowHide$.subscribe(
    (data:boolean) => {
      this.boolShowGTMDetails = data,
      error => console.log(error),
      console.log("winner winner chicken dinner");
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

基本上,更改检测不起作用,我们将不胜感激任何帮助,提前致谢!

Bea*_*341 5

好吧,我弄清楚了我的问题......

我在两个组件中都providers:[ShowHideService],创建了两个不同的服务实例。因此,我从两个组件中删除了它,只需在我的 app.modules 中调用它一次,一切就正常工作了。菜鸟移动我的端脸手掌-_-