Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable vs asObservable()?

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();
like image 209
vikas Avatar asked Feb 16 '17 11:02

vikas


People also ask

What is asObservable () in Angular?

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.

What is difference between BehaviorSubject and 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.

What is difference between observable and 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.

Why we use observable in Angular?

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.


1 Answers

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.

like image 61
Günter Zöchbauer Avatar answered Oct 20 '22 12:10

Günter Zöchbauer