我正在尝试从多个http请求创建一个Observable,似乎Forkjoin是答案,但是它们的调用次数取决于请求的数据(例如,您可以询问一年或一周的数据)。
这是当前代码:
Observable.forkJoin(
//Now the requests fires twice, but its
//possible this will be fired a 100+ times
this.markersHistoryService.fetch(macAddress, 1527853624000, 1528199224000),
this.markersHistoryService.fetch(macAddress, 1528199224000, 1528631224000)
).subscribe((history: MarkerData[], MarkerData[]): void => {
let firstResult:MarkerData = history[0];
const secondResult:MarkerData = history[1];
firstResult = firstResult.concat(secondResult)
subscribe.next([...firstResult]);
subscribe.complete();
});
它有效,但不是动态的。因此,我认为这应该是某种forloop,其中参数将生成为EPOCH时间,并且应根据要求设置这些参数的宽度。
第二次迭代:
const daysBetween = function (date1, date2) {
const one_day = 1000 * 60 * 60 * 24;
let difference_ms = date2 - date1;
return Math.round(difference_ms / one_day);
};
let observablesArr = [];
for (let i:number = 0; i < daysBetween(timeStart, timeEnd); i++) {
observablesArr.push(this.markersHistoryService.fetch(macAddress, 1516523557000, 1528199224000))
}
Observable.forkJoin(observablesArr).subscribe((history: MarkerData[]): void => {
subscribe.next([...history]);
subscribe.complete();
});
任何想法将不胜感激!
问候,布拉姆
答案 0 :(得分:0)
您可以创建一个数组并将请求推送到该数组,然后通过forkJoin
let observablesArr = []
yourArr.forEach((item) => {
observablesArr.push(item) // push you requests
})
Observable.forkJoin(observablesArr ). sunscribe(.....
答案 1 :(得分:0)
将所有请求推送到一个数组中。请求/可观察的最终数组应如下所示:
const serviceArray = [
this.markersHistoryService.fetch(macAddress, 1527853624000, 1528199224000),
this.markersHistoryService.fetch(macAddress, 1528199224000, 1528631224000)
]; // can be 1000+ items.
// now do following :
Observable.forkJoin(
serviceArray
).subscribe((resultArray): void => {
// resultArray[0] - will contain 1st item result
// resultArray[1] - will contain 2nd item result
subscribe.next([...firstResult]);
subscribe.complete();
});