首页 > 解决方案 > 从多个可观察值创建可观察值

问题描述

在我的一个组件中,我需要遍历一组 id 并为每个组件进行 API 调用。api 调用返回 observables,目前我只是订阅循环中的每一个并将其值添加到数组中。我不认为这很好,因为我正在单独订阅每个电话。有没有一种方法可以使用类似mergeMap或类似的东西来创建循环中所有组合值的可观察值?

这样我就有了一个可以订阅(或使用 HTML 中的异步管道)而不是很多的 observable?

这是我的控制器代码:

export class GraphTablesComponent implements OnInit {

  @Input() meta: any;
  @Input() entityId: number;
  kpiData: Array<any> = [];

  constructor(
    private apiService: ApiService
  ) { }

  ngOnInit() {
    this.getKpiData();
  }

  private getKpiData(): void {
    for (const m of this.meta) {
      this.apiService.post(`${Endpoints.KPIS}execute/${m._bid}/${this.entityId}`, {}).subscribe(d => this.kpiData.push(d));
    }
  }
}

标签: angularrxjs

解决方案


您可以使用ForkJoin来实现它

private getKpiData(): void {
    let requestArray = [];

    for (const m of this.meta) {
      requestArray.push(this.apiService.post(`${Endpoints.KPIS}execute/${m._bid}/${this.entityId}`, {}))
    }

    forkJoin(requestArray).subscribe(data => {
      this.response1 = data[0];
      this.response2 = data[1];
    });
}

如果您直接想在模板中添加它,

.ts

this.data$ =  forkJoin(requestArray)

.html

<ng-container *ngIf="data$ | async; let data">
   {{data | json}}
</ng-container>

推荐阅读