简体   繁体   English

我如何才能在 rxjs 的订阅中访问 c​​oncatMap 对象

[英]How can i have access to concatMap object in subscribe in rxjs

I use from() with pipe and concatMap and i would like to have access to the object in concatMap because i need it for doing a mapping after.我将 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
                )
              );
            }
          });

Is it possible to do that ?有可能这样做吗? Is there another way which can help me doing that ?有没有另一种方法可以帮助我做到这一点? Thanks谢谢

You could just pipe in a map to the inner observable inside the concatMap and send an object with both values.您可以将map通过管道传输到concatMap内部的内部 observable 并发送具有两个值的对象。

Try the following尝试以下

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
      )
    );
  }
});

If you want to avoid turning an array into a stream, you can instead merge an array of streams.如果您想避免将数组转换为流,则可以改为合并流数组。

You can use the closure from array.map to map each object into the results of its stream.您可以使用 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)
  )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM