I have an Angular service which keeps an private BehaviorSubject
so that it can read the value at any given time. It is private so that any component that uses it cannot manipulate it. Instead, a regular Observable
is exposed as public. The BehaviorSubject
is now a consumer of any data emitted by this observable.
public subheaderData$: Observable<SubheaderData>;
private subheaderDataSubject$: BehaviorSubject<SubheaderData> = new BehaviorSubject<SubheaderData>(null);
constructor(private repository: SubHeaderRepository) {
this.subheaderData$ = this.load();
this.subheaderData$.subscribe(this.subheaderDataSubject$);
}
As you can see, I am calling .subscribe
from my service, which makes my observable hot immediately. What I would like to accomplish is that a component which injects this service must subscribe to the public Observable
, and when that happens, the BehaviorSubject
should automatically be added as an observer, even though the component has no knowledge of it (due to it being private.
How can this be accomplished?
subheaderDataSubject$
to subscribe tosubheaderData$
only when there's at least one subscriber tosubheaderDataSubject$
? - martinsubheaderData$
which is in the service, I want the service to attach thesubheaderDataSubject$
as an observer. - blgrnboysubheaderData$
it should automatically subscribethis.subheaderDataSubject$
tosubheaderData$
. - martin