【问题标题】:How can I get multiple services call to finish before emitting an event如何在发出事件之前完成多个服务调用
【发布时间】:2018-08-25 22:20:42
【问题描述】:

您好,我正在使用 Angular 5。 我想要实现的是等到多个服务调用完成,我不知道我是否可以使用 forkJoin 运算符,因为服务调用取决于一个参数,例如:如果这个参数为 2,将会有两个调用这项服务。有没有办法让它以某种方式工作?

代码:

    for (let i = 0; i < this._periodQtty; i++) {
        this.service.getPastMonthData(i).subscribe(pastMonthData => {

            if (pastMonthData && pastMonthData.length > 0) {
                chartPoints = new Array<ChartPoint>();

                pastMonthData.forEach(pastMonthElement => {
                    point = this.buildChartPoint(pastMonthElement, timeSpan);

                    if (point)
                        chartPoints.push(point);
                });

                chartDataSets.push({
                    data: chartPoints,
                    backgroundColor: "#f44336",
                    borderColor: "#ba000d",
                    pointHoverBorderColor: "#ba000d",
                    pointHoverBackgroundColor: "#ff7961",
                    pointRadius: 3.5,
                    label: "prueba 2",
                    fill: false,
                    type: 'line',
                })
            }

            this._chartDataSets = chartDataSets;
            this.ChartDatasetsUpdated.emit(this._chartDataSets);
            })
        }

【问题讨论】:

标签: angular rest typescript rxjs


【解决方案1】:

我认为这可能会达到你想要的效果

import { range } from 'rxjs/observable/range';
import { map, toArray } from 'rxjs/operators';
import { forkJoin } from 'rxjs/observable/forkJoin';

const sources$ = range(0, this._periodQtty).pipe(
  map(i => this.service.getPastMonthData(i)),
  toArray()
);
sources$.subscribe(sources => {
  forkJoin(...sources).subscribe(allPeriodsData => {
    allPeriodsData.forEach((pastMonthData, monthIndex) => {
      ...
    });
  });
});

或者使用数组构建而不是可观察范围,

import { forkJoin } from 'rxjs/observable/forkJoin';

const sources = new Array(this._periodQtty).fill(null).map((x,i) => {
  this.service.getPastMonthData(i)
);
forkJoin(...sources).subscribe(allPeriodsData => {
  allPeriodsData.forEach((pastMonthData, monthIndex) => {
    ...
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-26
    • 1970-01-01
    • 2020-10-31
    • 2020-12-23
    • 1970-01-01
    相关资源
    最近更新 更多