我有3个依赖的rest api资源(可以说是可观察的),如下所示:
1st observate以用户数组的形式生成一个项,如下所示:

getUsers(): Observable<User[]>
    [
      {
        "id": 1,
        "name": "Peter",
        "surname": "Smith"
      },
      {
        "id": 2,
        "name": "John",
        "surname": "Wayne"
      },
      ...
    ]

2nd observate可用于获取分配给用户的地址,因此输入参数是user id,并返回一个一项作为地址数组:
getUserAddresses(user_id: string): Observable<Address[]>
    [
      {
        "id": 1,
        "city": "London",
        "street": "Wicombe 34"
      },
      {
        "id": 2,
        "city": "Paris",
        "street": "La fever 20"
      },
      ...
    ]

3rd observate可用于获取分配给用户的公司,因此输入参数是user id,并返回一个一项作为公司数组:
getUserCompanies(user_id: string): Observable<Company[]>
    [
      {
        "id": 1,
        "name": "Fintch CO",
        "state": "France"
      },
      {
        "id": 2,
        "name": "C&C inc.",
        "state": "USA"
      },
      ...
    ]

我想把这三个观察结果连成一个条目,这个条目将再次产生结果,它将包含用户数组及其附加地址数组和公司数组,如下所示:
    [
      {
        "id": 1,
        "name": "Peter",
        "surname": "Smith",
        "addreesses":
               [
                 {
                   "id": "1",
                   "city": "London",
                   "street": "Wicombe 34"
                 },
                 {
                   "id": "2",
                   "city": "",
                   "street": "La fever 20"
                 }
               ],
        "companies":
               [
                 {
                   "id": "1",
                   "name": "Fintch CO",
                   "state": "France"
                 },
                 {
                   "id": "2",
                   "name": "C&C inc.",
                   "state": "USA"
                 }
               ]
        }
      },
      {
        "id": 2,
        "name": "John",
        "surname": "Wayne",
        "addresses": [...],
        "companies": [...],
      },
      ...
    ]

在使用rxjs 6实现角度6时,操作符的组合应该是什么样子的?
非常感谢你的建议。

最佳答案

像这样的东西可以用

getUsers()
.pipe(
  switchMap(users => from(users)),
  mergeMap(user => forkJoin(getAddresses(user.id), getCompanies(user.id))
                   .pipe(map(data => ({user, addresses: data[0], companies: data[1] })))
  tap(data => data.user.addresses = data.addresses),
  tap(data => data.user.addresses = data.companies),
  map(data => data.user),
  toArray()
  )
)

应用于不同的用例,类似的链将在here中得到更详细的解释。

10-06 11:34