如何在发出事件之前让多个服务调用完成 [英] How can I get multiple services call to finish before emitting an event
本文介绍了如何在发出事件之前让多个服务调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我正在使用角度5. 我要实现的是等待多个服务调用完成,我不知道是否可以使用forkJoin运算符,因为服务调用取决于一个参数,例如:如果此参数为2,将有两个调用这项服务.有办法使它以某种方式工作吗?
Hello I'm working with angular 5. What I want to achieve is to wait until multiple services calls finish, I don't know if I can use forkJoin operator because the the service calls depends on a parameter, for example: If this parameter is 2, there will be two calls to this service. Is there a way to get this working somehow?
代码:
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);
})
}
推荐答案
我认为这可以实现您想要的
I think this might achieve what you want
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) => {
...
});
});
});
或者使用数组构建而不是可观察范围
Or with array building instead of observable range,
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) => {
...
});
});
这篇关于如何在发出事件之前让多个服务调用完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文