我有一个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解决方案,但不能完全解决它,也许是版本问题。我如何创建一个可观察的/等等。让我的循环等待我的数据完成处理?
非常感谢!
答案 0 :(得分:1)
使用RxJs运算符concatMap和toArray: concatMap等待可观察的api完成后再处理下一项。 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
})