【问题标题】:RxJS example of loading and enriching a list of items加载和丰富项目列表的 RxJS 示例
【发布时间】:2020-10-12 22:49:47
【问题描述】:

我想获取一个包含多个项目的数组,然后获取并向该数组中的每个项目添加附加数据。

在给定getItemsList 和getRelatedObject 的实现的情况下,如何实现getEnrichedItemsList 方法?

interface RelatedObject = {}

interface Item = {
  id: string;
  relatedObjectId: string;
}

interface EnrichedItem = Item & {
  relatedObject: RelatedObject ;
}

interface apiService = {
  getItemsList: (query: string) => Observable<Item[]>; // implemented
  getRelatedObject: (relatedObjectId: string) => Observable<RelatedObject>; // implemented
  getEnrichedItemsList: (query: string) => Observable<EnrichedItem[]>; // HOW TO IMPLEMENT?
}

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    这样的?

      getEnrichedItemsList(query: string): Observable<EnrichedItem []>{
        return this.getItemsList(query).pipe(
          mergeMap(items => from(items)),
          mergeMap(item => this.getRelatedObject(item.relatedObjectId).pipe(
            map(relatedObject => Object.assign(item,{relatedObject}))
          ))
        );
      }
    

    完整示例:https://stackblitz.com/edit/rxjs-ahllnu

    【讨论】:

    • toArray() 在管道的末端,它!非常感谢!
    【解决方案2】:

    使用forkJoin 同时执行多个请求,并发出与输入数组顺序相同的项目数组。

    getEnrichedItemsList(query: string): Observable<EnrichedItem[]> {
      return this.getItemsList(query).pipe(
        switchMap(items => forkJoin(items.map(item => this.enrichItem(item))))
      )
    }
    
    enrichItem(item: Item): Observable<EnrichedItem> {
      return this.getRelatedObject(item.relatedObjectId).pipe(
        map(relatedObject => ({ ...item, relatedObject } as EnrichedItem))
      )
    }
    

    这保证了丰富项目的最终顺序与this.getItemsList(query) 收到的相同,而使用from 和mergeMap 时可能不是这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-22
      • 2023-03-20
      • 2011-07-27
      • 2011-08-19
      • 2017-03-01
      • 2016-09-20
      • 2013-02-11
      相关资源
      最近更新 更多