I have a very simple scenario with an input field and bunch of sections that make API calls based on what is typed in that input field.
Now the input field itself is in a different component, so what I have done is create a behaviorSubject in a service, have a default value and then any time user changes the input field I just call another method within the service that internally calls next on the behaviorSubject.
Then within my different UI sections I subscribe to this behaviorSubject and want to check anytime the value changed make API calls. Note the API endpoints are different for each section but they need to get fired at the same time.
However, I'm unable to get this to work. Here is what I have so far
Code within my service changeService.ts:
valueChangedSubject: BehaviorSubject<any>: new BehaviorSubject({});
constructor() {}
valueHasChanged(updatedValue: any) {
this.valueChangedSubject.next(updatedValue);
}
Code within one component that fires the event:
valueChanged(changedVal: string) {
this.changeService.valueHasChanged({val: changedval});
}
Code within a component that subscribes to the behavior Subject:
this.changeService.valueChangedSubject.subscribe((val:any) => {
console.log('OK I am here ', val);
});
Problem is that the 'Ok I am here' gets printed first time on refresh, but there after any time I call the valueChanged() method it does not trigger the observable.
I know I am missing something related to 'hot observable' here. But what and how to do that? I tried to use share() or publish() but could not get it to work as I expected.
A BehaviourSubject is a hot observable. Hot means, even when there are now Subscribers the observables fires new values. I don't see any problem with your code you provided in your question. It looks fine.
Are you sure your valueChangesSubject
doesn't complete at any time? For example a Subject will complete when it handles an error.
You can check if your Observable completes by using onCompleted callback in subscription.
this.changeService.valueChangedSubject.subscribe(
next => console.log('OK I am here ', next),
error => console.error('Error. Observable completes', error),
() => console.log('Observable completes. No more values will be submitted')
);