I read this good article on Angular onPush Change Detection Strategy
at some potin he wrote:
It’s an anti-pattern to expose your subject to the outside world, always expose the observable, by using the asObservable() method.
but he doesn't explain why. Does this mean that I shouldn't do somthing like this?
export class ExampleComponent {
public drawerTrigger$ = new Subject<{}>();
}
and in the HTML
<button class="hamburgher-button" type="button"
(click)="drawerTrigger$.next($event)">
<i >menu</i>
</button>
if no, which is the proper way?
In general, you shouldn't expose Subject
s because this gives anyone using your service possibility to uncontrollably call drawerTrigger$.next()
even in incorrect use-cases.
Even worst situations is that anyone can use drawerTrigger$.error()
or drawerTrigger$.complete()
. Subjects have internal state and if they emit error
or complete
the Subject is marked as stopped and will never ever emit anything. If you expose your Subject
then you let anyone emit these notifications.
The officially recommended way of exposing Subjects from TypeScript classes is just forcing their types to Observable
. You don't need to use asObservable()
(RxJS itself doesn't internally use asObservable()
anywhere in its codebase):
export class ExampleComponent {
private drawerTriggerSubject = new Subject<{}>();
public drawerTrigger$: Observable<{}> = this.drawerTriggerSubject;
}
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