【问题标题】:Creating multiple async pipes of unknown number创建多个未知数量的异步管道
【发布时间】:2020-09-15 08:15:09
【问题描述】:

我正在使用 Angular 5 并使用带有我的 NGRX 库的选择器加载项目列表。我的选择器返回一个项目列表,我使用异步管道在页面上动态创建选项卡。现在,当用户单击选项卡时,我想触发另一个选择器以从我的 NGRX 存储中获取数据,该存储可能存在也可能不存在,广告可能会触发 API 请求并由减速器更新。一切正常。

我的问题是,我有可变数量的选项卡,这可能会触发多个异步请求,我想将每个请求的响应绑定到正确的选项卡。我不知道该怎么做? 我有这样的代码:

this.store$ .select(getTabContent(id)).pipe(takeUntil(this.onDestroy$), take(1)).subscribe((data) => { ...};

但宁愿使用异步管道,我不确定这是否是使用反应库的最佳方法。在我的情况下,如何创建可变异步管道并能够绑定到特定选项卡?

【问题讨论】:

  • 你能创建一个 StackBlitz 吗?

标签: angular rxjs rxjs5 async.js rxjs-pipeable-operators


【解决方案1】:

您需要在某处共享选项卡的 id,然后您可以使用 switchMap 和 combineLatest 来获取所有选项卡的通知。

ids$ = new BehaviorSubject([1, 2, 3]); // initial tabs

ngOnInit() {
  this.tabs$ = ids$.pipe(
    // creates an array of selectors
    switchMap(ids => combineLatest(ids.map(id => this.store.select(getTabContent(id))))),
    takeUntil(this.onDestroy$),
  );
}

addTab() {
  this.ids$.next([...this.ids$.value, 4]);
}

在模板中

<ng-container *ngIf="tabs$ | async as tabs">
  <tab *ngFor="let tab of tabs">{{ tab | json }}</tab>
</ng-container>
<a (click)="addTab()">Add Tab</a>

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多