我如何在rxjs中访问subscribe中的concatMap对象



我将from((与pipe和concatMap一起使用,我希望能够访问concatMap中的对象,因为之后我需要它来进行映射。

from(objects)
.pipe(
concatMap(object => // i need to have access to object in subscribe
defer(() =>
this.service.getObjectInfors(object.id)
)
)
)
.subscribe(objectInfos => {
if (objectInfos) {
this.objectsTab.push(
this.mappingObject(
object, // i need object in this mapping
objectInfos
)
);
}
});

有可能做到吗?有其他方法可以帮助我做到这一点吗?感谢

您可以通过管道将map发送到concatMap内部的内部可观察对象,并发送一个同时具有这两个值的对象。

尝试以下

from(objects).pipe(
concatMap(object =>
defer(() =>
this.service.getObjectInfors(object.id).pipe(
map(objectInfos => ({
obj: object,
infos: objectInfos
}))
)
)
)
)
.subscribe((data: any) => {
// access `data.obj` and `data.infos` here
if (data.infos) {
this.objectsTab.push(
this.mappingObject(
data.obj,
data.infos
)
);
}
});

如果您想避免将数组转换为流,可以合并流的数组。

可以使用array.map中的闭包将每个对象映射到其流的结果中。

const infoObjectsCalls = objects.map(object => 
defer(() => this.service.getObjectInfors(object.id)).pipe(
filter(objectInfos => objectInfos != null),
map(objectInfos => ({
object,
objectInfos 
}))
)
);
merge(...infoObjectsCalls).subscribe(mappingObject =>
this.objectsTab.push(
this.mappingObject(mappingObject)
)
);

最新更新