我可以通过以下方式订阅 RXJS observable 吗?
Can I subscribe to an RXJS observable the following way?
在我的 Angular 组件中,我想订阅很多选择器,为了减少样板,我尝试了以下订阅方式:
this.store.select(selectFilloutId)
.subscribe(filloutId => this.filloutId=filloutId);
它似乎按照我想要的方式工作,我的组件中的 filloutId
获得了正确的值,但我不完全确定没有我无法避免的不良副作用见。
我的问题是:这是一个好方法,还是我应该完全避免这种方法?
提前致谢!
只要您在某个时候取消订阅,该方法就没有问题。如果您不退订,一个不想要的副作用是,在您完成订阅后,您会留下旧的订阅。这最终可能会导致内存泄漏。
如果您使用从特定选择器返回的值来显示模板中的内容,我会在模板中订阅它。这将为您管理订阅生命周期,在我看来比手动订阅更好。如果可以避免,我宁愿不手动订阅。
<ng-container *ngIf="fillOutId$ | async; let fillOutId"></ng-container>
如果您依赖 fillOutId$
来执行其他异步操作,我会使用管道。例如,如果你想得到一个基于 fillOutId$
:
的列表
list$ = this.fillOutId$.pipe(
// map, switchMap, whatever you need to do here
)
然后,在模板中订阅这个:
<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>
顺便说一句,ngrx
有一个名为 @ngrx/component
的库,它可以让你将上面的代码写成:
<ng-container *ngrxLet="fillOutId$; let fillOutId"></ng-container>
这会让您订阅可观察对象,但如果值为 falsy,则不会阻止渲染。
在我的 Angular 组件中,我想订阅很多选择器,为了减少样板,我尝试了以下订阅方式:
this.store.select(selectFilloutId)
.subscribe(filloutId => this.filloutId=filloutId);
它似乎按照我想要的方式工作,我的组件中的 filloutId
获得了正确的值,但我不完全确定没有我无法避免的不良副作用见。
我的问题是:这是一个好方法,还是我应该完全避免这种方法?
提前致谢!
只要您在某个时候取消订阅,该方法就没有问题。如果您不退订,一个不想要的副作用是,在您完成订阅后,您会留下旧的订阅。这最终可能会导致内存泄漏。
如果您使用从特定选择器返回的值来显示模板中的内容,我会在模板中订阅它。这将为您管理订阅生命周期,在我看来比手动订阅更好。如果可以避免,我宁愿不手动订阅。
<ng-container *ngIf="fillOutId$ | async; let fillOutId"></ng-container>
如果您依赖 fillOutId$
来执行其他异步操作,我会使用管道。例如,如果你想得到一个基于 fillOutId$
:
list$ = this.fillOutId$.pipe(
// map, switchMap, whatever you need to do here
)
然后,在模板中订阅这个:
<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>
顺便说一句,ngrx
有一个名为 @ngrx/component
的库,它可以让你将上面的代码写成:
<ng-container *ngrxLet="fillOutId$; let fillOutId"></ng-container>
这会让您订阅可观察对象,但如果值为 falsy,则不会阻止渲染。