如何等待我的Angular订阅在循环内完成?

问题描述 投票:0回答:1

我有一个Angular 6应用程序,我循环遍历一个数组并为我的组件内的数组中的每个项目创建一个API。我想等到收到数据并且在向数组中的下一个项目发出请求之前已经运行了所有逻辑。现在,它只是对数组中的最后一项提出多个请求。在进入下一个请求之前,如何让循环等待响应?

for (var index = 0; index < data.length; index++) {
    this.deviceService.getMeasurementData(data[index].id, this.authService.userSession.authToken, this.filterModel.fromDate, this.filterModel.toDate)
    .subscribe(data => {
               //logic where I transform data to be displayed in the view


    })

}

我试图实现THIS解决方案,但不能让它工作,也许这是一个版本问题。我怎样才能创建一个observable / etc。让我的循环等待我的数据完成处理?

非常感谢!

angular typescript loops observable
1个回答
1
投票

使用RxJs运算符concatMap和toArray:concatMap在处理下一个项目之前等待api observable完成。 toArray收集结果,直到完成所有处理。

from(data).pipe(
    concatMap(item => this.deviceService.getMeasurementData(item.id, this.authService.userSession.authToken, this.filterModel.fromDate, this.filterModel.toDate)),
    toArray()
).subscribe(responses => {
... // array of all the data returned from api
})
© www.soinside.com 2019 - 2024. All rights reserved.