I have an Angular service with a boolean property called must_checkout. My service also contains a property called observable_must_checkout which is a BehaviorSubject looking into must_checkout.
Then, In my component I subcribe to observable_must_checkout.
This works and the component receives the event the first time must_checkout changes. However this only fires once, and subsequent changes to must_checkout are not working:
Service:
import { Injectable, Input, Output } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export class OrderingService
{
must_checkout: boolean;
observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
constructor([...])
{
this.observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
}
ChangeSomething()
{
console.log("changing the value here...");
this.must_checkout = true;
}
}
Parent component:
import { Component, OnInit } from '@angular/core';
import { OrderingService } from 'src/app/services/ordering.service';
@Component({
selector: 'app-settle',
templateUrl: './settle.component.html',
styleUrls: ['./settle.component.css']
})
export class SettleComponent implements OnInit
{
constructor(private OrderingService: OrderingService) { }
ngOnInit()
{
this.basket = new OrderingService();
this.basket.observable_must_checkout.subscribe((newValue: boolean) => { alert("value changed: " + newValue) });
}
ngOnDestroy() {
this.basket.observable_must_checkout.unsubscribe();
}
}
I'm not seeing a call to next(), which is how you fire new events to the current subscribers of your BehaviorSubject. You are looking for something like this.
ChangeSomething()
{
console.log("changing the value here...");
this.observable_must_checkout.next(true);
}
https://www.learnrxjs.io/subjects/
Also, you don't need to intialize the subject in the constructor since you do it a few lines above:
observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
constructor([...])
{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With