问题
I have a simple scenario:
service.ts:
private showComposeBoxAction = new BehaviorSubject<boolean>(null);
showComposeBox = this.showComposeBoxAction.asObservable();
openComposeBox(event:boolean) {
console.log("in openComposeBox");
this.showComposeBoxAction.next(event);
}
Component.ts:
constructor(
private _service: Service,
) {
this.subscriptions.add(
this._mailingService.showComposeBox.subscribe(event => {
if (event) {
this.displayCompose = true;
console.log("showComposeBox displayCompose", this.displayCompose);
}
})
);
}
component2.ts:
showComposeBox() {
if (this.count === 0) {
this._service.openComposeBox(true);
}
}
I have logged a msg within openComposeMsg(). Problem I am facing is that first time I am correctly subscribing to showComposeBox observable but 2nd time when subscribing even when next is not called because msg "in openComposeBox" does not log into console.
Unable to understand behavior of BehaviorSubject. What am I doing wrong?
回答1:
I solved my problem with guidance of JB Nizel and Suren Srapyan. By replacing behavior subject with subject. As observable is subscribed in constructor it triggered and uses current saved value of behavior subject which was set to true previously by other function.
Took reference from This SO But now facing another issue that openComposeBox is called and msg is logged even than observable is not subscribed. I will update answer when I get solution.
来源:https://stackoverflow.com/questions/51318977/subscribing-to-observable-even-when-next-is-not-called-on-behaviorsubject