Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 subscribe to boolean from service

Tags:

angular

I have a service that has a changing boolean value, I want to subscribe to that boolean change in a component. How can this be achieved?

here is my service...

private subBoolShowHideSource = new Subject<boolean>();

subBoolShowHide$ = this.subBoolShowHideSource.asObservable();


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

and here is the component I am trying to get to read the bool value...

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");
    }
  );
}

Basically the change detection isn't working, any help would be much appreciated, thanks in advance!

like image 560
Bean0341 Avatar asked Dec 31 '25 18:12

Bean0341


2 Answers

Well I figured out my problem....

I had in both my components providers:[ShowHideService], this of course creates two different instances of the service. So I removed this from both components and simply call it once in my app.modules and everything is working properly. Rookie move on my end facePalm -_-

like image 141
Bean0341 Avatar answered Jan 03 '26 12:01

Bean0341


You have some formatting issues in your subscription. This should work:

   this.subscription = this.service.subBoolShowHide$.subscribe(
       (data:boolean) => { this.boolShowGTMDetails = data },
       error => console.log(error),
       () => console.log("winner winner chicken dinner")
   );
like image 22
Sasxa Avatar answered Jan 03 '26 11:01

Sasxa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!