Search code examples
angularobservablebehaviorsubject

Use in html the async pipe => ¿BehaviorSubject or Observable?


I have a doubt, I the project I'm working on, I'v seen this:

private _isReady$: BehaviorSubject<boolean> = new <boolean>(false);
get IsReady$(): Observable<boolean> {
    return this._isReady$.asObservable();
}

And then, In the html template:

{{ isReady$ | async}}

Why not define the behaviorSubject as public, and use it direcly in the html with the async pipe? What is the difference/benefit returning that behaviour subject as an observable to use it in the html?


Solution

  • The reason being BehaviorSubject(_isReady$) private is that only a particular service should be allowed to emit the observable (no other components or service should be allowed to do so).

    But others can only subscribe to it using a publicly accessible Observable IsReady$