问题
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?
Code:
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);
})
}
回答1:
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) => {
...
});
});
来源:https://stackoverflow.com/questions/49327693/how-can-i-get-multiple-services-call-to-finish-before-emitting-an-event