In my Angular component, I want to subscribe to a lot of selectors, and to reduce the boilerplate, I tried subscribing the following way:
this.store.select(selectFilloutId)
.subscribe(filloutId => this.filloutId=filloutId);
It seems to be working the way I want it, the filloutId
in my component gets the correct value, but I'm not entirely sure that there are no unwanted side effects of which I can't see.
My question is: Is this a good approach, or should I avoid this entirely?
Thanks in advance!
There's nothing wrong with that method as long as you unsubscribe from it at some point. An unwanted side effect, if you do not unsubscribe, would be that you would have old subscriptions lying around after you are done with them. This may eventually lead to memory leaks.
If you are using the value that's returned from that particular selector to display something in a template, I would just subscribe to it in the template. This will manage the subscription lifecycle for you, and in my opinion is nicer than manually subscribing. I prefer not to manually subscribe should I be able to avoid it.
<ng-container *ngIf="fillOutId$ | async; let fillOutId"></ng-container>
If you are relying on fillOutId$
to perform other async operations, I would utilise pipes. For example, if you want to get a list of something based on fillOutId$
:
list$ = this.fillOutId$.pipe(
// map, switchMap, whatever you need to do here
)
Then, subscribe to this in the template:
<ng-container *ngFor="let item of list$ | async; let item">
<a-component-with-list-item-as-input
[item]="item"
></a-component-with-list-item-as-input>
</ng-container>
As an aside, ngrx
has a library called @ngrx/component
which will let you write the above as:
<ng-container *ngrxLet="fillOutId$; let fillOutId"></ng-container>
This will let you subscribe to the observable, but not block rendering should the value be falsy.