首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用嵌套数组链接rxjs 6可观测值

用嵌套数组链接rxjs 6可观测值
EN

Stack Overflow用户
提问于 2020-02-14 16:49:40
回答 1查看 334关注 0票数 2

我必须对API执行3次依赖请求。

  1. ,第一个是用户id的数组,第二个是迭代用户id的数组,每个迭代都是一个与用户相关的项目id数组,第三个是
  2. ,它必须迭代项目id的数组和与项目相关的数据。

我想要这样的结果:

代码语言:javascript
复制
[{'username': 'richard', projects: [{"id": 1, "name": "test"}]}, ...]

但我完全被mergeMap,forkJoin等困住了。

我试过的事情是:

代码语言:javascript
复制
getUserTeamMembers(): Observable<any> {
return this.http.get(`${environment.serverUrl}/user/profil`).pipe(
  mergeMap((teamUsers: any) =>
    this.http.get(
      `api/user/${teamUsers.data._id}/team`
    )
  ),
  mergeMap((teamUsers: any) =>
    forkJoin(
      ...teamUsers.data.map((user: any) =>
        this.http.get(`api/user/${user.id}`)
      )
    )
  ),
  map((res: any) =>
    res
      .map((user: any) => {
        if (user.data) {
          return {
            firstname: user.data.local.firstname,
            lastname: user.data.local.lastname,
            email: user.data.local.email,
            projects: user.data.local.projects,
            language: user.data.local.lang
          };
        }
      })
      .filter((user: any) => user !== undefined)
  ),
  tap(t => console.log(t)),
  catchError(err => throwError(err))
);}

我尝试了这么多事情,但我不知道如何填充我的项目数组,这些项目目前只包含id,而不包含与数据相关的数据:

代码语言:javascript
复制
[{'username': 'richard', projects: ['id1', 'id2']}, ...]
EN

回答 1

Stack Overflow用户

发布于 2020-02-15 08:02:31

做了一个类似的例子,希望能把这个想法弄清楚。

当然,不是使用http,而是使用of使其本地化

并将最终结果存储在一个名为results的数组中。

我们有一个源来获取所有用户的列表,另一个给定用户id的源将返回这个用户的项目id projectList的列表,最后一个提供一个项目id的源将返回它的详细信息(projcectsDetails)

代码语言:javascript
复制
    let users = of([ 1, 2, 3 ])
    let projectsList = (userId) => of([ userId, userId*2 ]) 
    let projectsDetails = (projectId) => of({ id: projectId, details: `details about ${projectId}` })


    let results = [];

    users
    .pipe(
      tap(users => {
        users.forEach(userId => results.push({ userId, projects: [] }));

        return users
      }),
      switchMap(users => forkJoin(users.map(userId => projectsList(userId)))),
      switchMap(projectsArray => forkJoin(
          projectsArray.map(
            oneProjectArray => 
            forkJoin(oneProjectArray.map(projectId => projectsDetails(projectId)))
          )
        )
      ),
      tap(projectDetailsArray => {
        projectDetailsArray.forEach((projectsArray, index) =>{
          results[index]['projects'] = [ ...projectsArray ]
        })
      })
    )
    .subscribe(() => console.warn('final',results))

解释

代码语言:javascript
复制
  1- initalize the result array from the given users
  [ 
   { userId: X, projcts: [] }, 
   { userId: Y, projcts: [] }, 
    ....
  ]

  2- for each give users we want the projects ids he/she has
  so the first switchMap will return (in order)
  [
   [ 1, 2, 3, ...] project ids for the first user,
   [ 8, 12, 63, ...] project ids for the second user,
   ...
  ]

  3- in the second switchMap we iterate over the previous array
  (which is an array that each item in it is an array of projects ids)

  so we needed two forkJoin the outer will iterate over each array of projects ids(the big outer 
  array previously mentioned)
  the inner one will iterate over each single project id and resolve it's observable value(which is the
  project details)

  4- finally in the tap process we have an array of array like the 2nd step but this time each
  array has the projects details and not the projects ids

  [
   { userId:1, projects: [ { id:1, details: 'details about 1' }, { id:2, details: 'details about 2' }]},
   { userId:2, projects: [ { id:2, details: 'details about 2' }, { id:4, details: 'details about 4' }]},
   { userId:3, projects: [ { id:3, details: 'details about 3' }, { id:6, details: 'details about 6' }]}
  ]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60230485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档