角度模板语法将异步数组分配为多个变量



在JS中,有一种优雅的方法可以将值从给定数组传递到新变量,如下所示:

let [a, b, c] = [1, 2, 3]; // a = 1, b = 2, c = 3

我想知道我是否可以使用 Angular 的 HTML 语法实现同样优雅的方式,如下所示:

// TS
this.obs1$: Observable<ObsType1> = ...;
this.obs2$: Observable<ObsType2> = ...;
this.combined$ = combineLatest(this.obs1$, this.obs2$);
// HTML
<div *ngIf="combined$ | async as [valOfObs1, valOfObs2]">
...
</div>

可观察combined$是来自 RxJS 的 combineLatest 的结果,它应该向我返回数组值数组。

显然,文档中没有任何暗示这是可能的。因此,我不得不采取这样的解决方法:

this.obs1$: Observable<ObsType1> = ...;
this.obs2$: Observable<ObsType2> = ...;
this.combined$: Observable<{obs1: ObsType1, obs2:: ObsType2}>;
this.combined$ = combineLatest(this.obs1$, this.obs2$).pipe(
map(([obs1, obs2]) => ({obs1, obs2});
);
// HTML
<div *ngIf="combined$ | async as combined">
{{ combined.obs1.foo}}
{{ combined.obs2.bar}}
</div>

最新更新