angular根据条件(是否存在内存泄漏?)使用async为模板分配不同的可观察对象



我需要基于一些标志来呈现来自不同ngrx存储的数据。两个存储都提供相同类型的数据。

方法1

<ng-contaier *ngIf="flag$ | async; else anotherStoreData">
<ng-container *ngIf="store1$ | async as store1">
<div>{{ store1?.prop1 }}</div>
<div>{{ store1?.prop2 }}</div>
</ng-container>
</ng-contaier>
<ng-template #anotherStoreData>
<ng-container *ngIf="store2$ | async as store2">
<div>{{ store2?.prop1 }}</div>
<div>{{ store2?.prop2 }}</div>
</ng-container>
</ng-template>
flag$: Observable<boolean>
store1$: Observable<Store>
store2$: Observable<Store>
ngInit() {
flag$ = streamService.userNewStore();
store1$ = this.store.select(<someselector1>);
store2$ = this.store.select(<someselector2>);
}

方法2

<ng-container *ngIf="store$ | async as store">
<div>{{ store?.prop1 }}</div>
<div>{{ store?.prop2 }}</div>
</ng-container>

store$: Observable<Store>
ngInit() {
streamService.userNewStore()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((flag) => {
store$ = flag ? this.store.select(<someselector1>) : this.store.select(<someselector2>);
});
}

在方法1中,我正在复制模板,这对于小模板来说很好,但如果它很大,那么我会考虑方法2。

在Approach2中,streamService可以随时更改标志,在这种情况下,使用异步管道的模板中的上一个订阅会发生什么。这会导致内存泄漏吗?

我还有其他可以使用的替代品吗,请提出建议。

刚刚检查了异步管道的源代码,如果Observable发生更改,它似乎将取消订阅。

你可以在文件的第100行看到这一点:

if (obj !== this._obj) {
this._dispose();
return this.transform(obj as any);
}

如果传入的值不是当前保存在内存中的值,它将调用this.dispose,然后取消订阅。

考虑到这一点,我肯定更喜欢的第二种方法

您可以在条件运算符中使用可观察的flag$来确定数据源:

<ng-container *ngIf="((flag$ | async) ? store1$ : store2$) | async as store">
<div>{{ store?.prop1 }}</div>
<div>{{ store?.prop2 }}</div>
</ng-container>  

有关演示,请参阅此stackblitz。

最新更新