【问题标题】:Angular template syntax assign async array as multiple variablesAngular 模板语法将异步数组分配为多个变量
【发布时间】:2018-08-22 16:57:34
【问题描述】:

在 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$ observable 是来自 RxJS 的 combineLatest 的结果,它应该返回一个数组值数组。

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

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

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      相关资源
      最近更新 更多