首页 > 解决方案 > 使用 RxJS 运算符从 API 获取并获取另一个然后组合结果

问题描述

我是 RxJS 的初学者,我的前端使用 angular。我有一个需要获取团队(Team [])的案例。

并使用该团队 id 获取所有成员 (Member[])。我需要返回每个团队的成员列表(团队,成员 [])。

如何使用 RxJS 运算符执行此操作?


例如:

来自 Teams API:[{team_id: number, 'others'}, ...]

来自会员 API:[{member_id: number, member_name: string}, ...]

我需要将数据组合到:[{team_id: number, members: [{member_id: number, member_name: string}, ...], ...]

标签: angularrxjs

解决方案


this.teamService.getTeams()
   .pipe(
     switchMap(teams => {
      // in here we will get all teams in teams variable
      const memberRequests = [];

      // we will create an array of member requests based on the teams
      teams.forEach(team => {

        const request = this.memberService.getMembersByTeamId(team.id)
          .pipe(map(members => { 
             // here we create new object which contains the team and its correspoing members
             return {...team, members} 
           }))

         memberRequests.push(request)
      })

      // in here we will call all member requests in parallel, and once all requests are completed we will get the response as array
      return forkJoin(memberRequests)
    }) 
   ).subscribe(items => {
     console.log(items)
   })

在上面的代码中,您将获得以下团队及其对应的成员,

[{team_id: number, members: [{member_id: number, member_name: string}, ...], ...]


推荐阅读