When I started learning angular I read about angular subjects and observables and started using it. In many open source code, I have seen that Subjects are not exposed directly to components but they are shared by making them Observables. So now I want to share my learning with you.
The asObservable() operator can be used to transform a subject into an observable. This can be useful when we like to expose the data from the subject, but at the same time prevent new data pushed back into the subject:
Difference Between Observables & Subjects:
// Note: Here its just a difference which covers this blog
Observables: We can get value whenever we subscribe to observables. It's only one-directional.
Subjects: Subjects are a special type of observable. In this case, we can get value by subscribing to it and also push back new value by using next() method.
Case 1: Subjects Without asObservable():
let's say we have a service in which we have declared a subject like this
now this Behaviour Subject is used to show or hide a spinner in a component so used like below
This is so far so good. But as we have used subject directly in the component so it is always open to publishing new change from this component by using next() method ( As by Definition subjects are both Observable and Observer)
like if in component functions showLoader() or hideLoader() user can directly use like
this.loaderService.showSpinner.next(true)
but this is not a good practice. We should make modifications only in service so to do it asObservable() comes in use.
Case 2: Subjects With asObservable():
Now service code will look something like this
Step 1: showSpinner is made Private so no component/directives where we use it can modify it
Step 2: An Observable is created by using asObservable()
Step 3: In Component Value is read from Observables instead of Subjects.
My Youtube Channel :