gpt4 book ai didi

javascript - 将 MergeMap 与从另一个 observable 接收的数据数组一起使用 - RxJs Angular

转载 作者:行者123 更新时间:2023-12-04 09:43:43 24 4
gpt4 key购买 nike

我有一个 fetchDrives 方法,它将返回一个 observable,订阅时将返回一个驱动器列表

this.fetchDrives(points).subscribe(drives => {
console.log(drives);
});

假设我订阅的驱动器阵列看起来像这样
[ {driveId: 1}, {driveId: 2}, {driveId: 3} ]

现在我需要一个一个地使用 driveId 并通过将 driveId 传递给每个 api 调用来进行三个调用(三个因为驱动器数组的长度是 3 )。我需要一次将 driveId 传递给下面的方法一个并获取纬度和 lon 并将三个调用的结果存储在一个数组中。
this.getLatLong(driveId).subscribe( res => console.log(res))

res 将包含一个对象,如 { lat: 12, lon: 54 }
我不想做两个订阅,有没有一种方法可以使用 Rxjs 操作符,并使用以前的 observable 的结果通过一个订阅来实现这一点,循环遍历驱动器数组并对 getLatLong 进行三次调用使用方法 mergeMap因为调用的顺序无关紧要并将这三个调用的结果存储在一个数组中?

我尝试使用 scan 运算符进行循环,但未能使用它来获得所需的输出

我在这里先向您的帮助表示感谢 :)

最佳答案

如果请求的顺序无关紧要,您可以使用 RxJS forkJoin 同时进行调用的方法。我也用过 switchMap 一旦源 observable ( this.fetchDrives(points) ) 发出,操作符就会切换 observable。尝试以下

locations: any;

this.fetchDrives(points).pipe(
switchMap((drives) => {
let source = Object.create(null);
for (let i = 0; i < drives.length; i++) {
source[drives[i]['driveId']] = this.getLatLong(drives[i]['driveId']);
}
return forkJoin(source);
})
).subscribe(
response => {
this.locations = response;
},
error => {
// handle error
}
);
变量 locations将是形式
// 'driveId': { lat: 12, lon: 54 }

{
'1': { lat: 12, lon: 54 },
'2': { lat: 12, lon: 54 },
'3': { lat: 12, lon: 54 }
}
更新:对象输出数组
forkJoin 返回一组对象您可以发送一组 observables 作为参数。例如。 forkJoin([obs1, obs2, ...]) .在前面的例子中,我们发送了一个对象作为参数( forkJoin({'name1': obs1, 'name2': obs2, ...}) ,所以输出也将是一个对象。
locations: any = [];

this.fetchDrives(points).pipe(
switchMap((drives) => {
return forkJoin(drives.map(drive => this.getLatLong(drive['driveId'])));
})
).subscribe(
response => {
this.locations = response;
},
error => {
// handle error
}
);
locations将是形式
[
{ lat: 12, lon: 54 },
{ lat: 12, lon: 54 },
{ lat: 12, lon: 54 }
]

关于javascript - 将 MergeMap 与从另一个 observable 接收的数据数组一起使用 - RxJs Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62213554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com