小编the*_*lob的帖子

如何按顺序使用 RxJS observables?

事情是这样的:我有一个 HTTP get 请求,它返回一个 JSON 对象列表。使用 RxJS 我订阅接收该列表的数据。现在,对于该列表中的每个对象,我想执行另一个 HTTP 请求,然后将该请求的结果放入一个数组中。

到目前为止,我已经能够做到这一点,但我似乎无法弄清楚如何用数据维护初始列表的顺序。这可能与整个 Observable 机制是异步的这一事实有关。

这是我的代码:

    ngOnInit(): void {
    this.shiftInformationService.getShifts("2016-11-03T06:00:00Z", "2016-11-06T06:00:00Z")
        .subscribe(shifts => {
            shifts.forEach(shift => {
                this.addDataToAreaChart(shift.startDateTime, shift.endDateTime, shift.description);
            });
        });

}

addDataToAreaChart(startDate: string, endDate: string, description: string) {
    this.machineStatisticsService
        .getCumulativeMachineStateDurations(startDate, endDate)
        .subscribe(s => {
            this.areaChartData = [];
            this.areaChartData.push(new AreaChartData(startDate, endDate, description, s));
        });
}
Run Code Online (Sandbox Code Playgroud)

我想要的是shifts.forEach在推送areaChartData数组中的数据时保持从循环调用的顺序。

有任何想法吗?帮助将不胜感激!

更新:解决了!

最终代码:

ngOnInit(): void {
    var startDate = new Date();
    startDate.setDate(startDate.getDate() - 3);

    this.shiftInformationService.getShifts(DateUtil.formatDate(startDate), DateUtil.formatDate(new Date()))
        .subscribe(shifts => {
            Observable.from(shifts) …
Run Code Online (Sandbox Code Playgroud)

javascript rxjs typescript angular

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

angular ×1

javascript ×1

rxjs ×1

typescript ×1