简体   繁体   English

Angular Map 并订阅 Observable pipe

[英]Angular Map and Subscribe in Observable pipe

I need your help in RxJS.我需要你在 RxJS 的帮助。

I made this code, that's needed to fetch an API, and for returned element, get this element type from another API.我编写了这段代码,这是获取 API 所需的,对于返回的元素,从另一个 API 获取此元素类型。 This code works fine, but it return an Observable for 'type' property instead of "string" only.这段代码工作正常,但它返回一个 Observable 用于 'type' 属性,而不是仅返回“string”。 Do you know how to achieve this?你知道如何实现这一目标吗? Thanks a lot.非常感谢。

combineLatest([
  this.service.list().pipe(
   map(items =>
     items.map(item => {
       item['type'] = this.getType(item.id);
       return item;
     })
    ),
    map(items => items.map(item => ({
      id: item.id,
      type: item['type'],
    })))
 ),
 this.form.valueChanges,
]).subscribe()

You're assigning the Observable to the property instead of it's response.您将Observable分配给属性而不是它的响应。 You'd need to use RxJS forkJoin and Array#map with a higher order mapping operator like switchMap .您需要使用 RxJS forkJoinArray#map以及像switchMap这样的高阶映射运算符。

Try the following尝试以下

combineLatest([
  this.service.list().pipe(
    switchMap((items: any) =>             // <-- switch to another observable
      forkJoin(                           // <-- multiple parallel requests
        items.map(item => 
          this.getType(item['id']).pipe(
            map((type: any) => ({         // <-- map back to original item with added type
              ...item,
              type: type
            }))
          )
        )
      )
    )
  ),
  this.form.valueChanges,
]).subscribe()

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

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