首页 > 解决方案 > API 返回一个我需要解析的数组;每个项目一个请求

问题描述

我有从后端返回的重复数据结构(可观察),它看起来像:

[{
     id:1,
     userId: 111,
     name: '',
     children :[
      { 
        id:3,
        userId: 333,
        name: '',
        children: [...]
      }
     ]
    },
    {
     id:2,
     userId:111,
     name:'',
     children: [...]
   }]

我有另一个通过用户 ID 返回用户名的端点。我需要使用每个 ID 调用此服务并将返回的名称映射到结构。有没有什么漂亮的解决方案可以使用 RxJs 运营商实现这一目标?

标签: rxjsobservable

解决方案


您可以尝试以下方法。有关详细信息,请参阅内联评论。

// fetchStruct is a function that returns an Observable which notifies the initial structure
const struct$ = fetchStruct();
// here we start the RxJs pipe transformation
struct$.pipe(
  // when struct$ emits the initial structure we pass the control to another observable chain
  // this is done via the concatMap operator
  concatMap(beStruct => {  // beStruct is the structure returned by the back end
    // from beStruct we construct an array of Observables
    // fetchName is a function that returns an Observable that emits when the name is returned
    arrObs = beStruct.map(el => fetchName(el.id))
    // with forkJoin we execute all the Observables in the array in parallel
    forkJoin(arrObs).pipe(
      // forkJoin emits when all Observables have notified and it will emit
      // an array of values with the same order as arrObs
      // we can therefore loop through this array to enrich beStruct with the names
      map(names => {
        names.forEach((n, i) => beStruct[i].name = n);
        return beStruct;
      })
    )
  })
)

这是一个非常典型的 RxJs 案例。您可能会在此博客中找到其他一些常见模式。


推荐阅读