I'm new to Angular2 and I'm just curious to know That If I do a subscribe on _showNavBar
or on showNavBarEmitter
both works same(see below code i'm using). is there any difference?
public _showNavBar: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
public showNavBarEmitter: Observable<boolean> = this._showNavBar.asObservable();
asObservable() The purpose of this is to prevent leaking the "observer side" of the Subject out of an API. Basically to prevent a leaky abstraction when you don't want people to be able to "next" into the resulting observable.
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities. An observable can be created from both Subject and BehaviorSubject using subject.
While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. Every Subject is an Observable.
Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.
asObservable
makes the original subject inaccessible for subscribers. This way you can limit who can only subscribe and who can also emit values.
For this to take effect you would need to make _showNavBar
private
though.
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