Observable vs asObservable()?

2020-07-11 10:03发布

问题:

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();

回答1:

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.