Rxjs - 使用 observables 作为值重新映射对象

Pat*_*cay 5 reactive-programming object-properties rxjs reactivex angular

我得到了一个这样的可观察对象:

  const original = Observable.of({
    a: this.http.get('https://jsonplaceholder.typicode.com/todos/11'),
    b: this.http.get('https://jsonplaceholder.typicode.com/todos/22'),
    c: this.http.get('https://jsonplaceholder.typicode.com/todos/33')
  });
Run Code Online (Sandbox Code Playgroud)

我需要解析内部 observables 并在订阅处理程序中得到类似的东西:

  {
    a: ResponseFromServer,
    b: ResponseFromServer,
    c: ResponseFromServer,
  }
Run Code Online (Sandbox Code Playgroud)

我应该如何解决这个问题?

谢谢。

编辑:我已经想通了,请阅读下文。

似乎没有多少人知道 *Map 运算符曾经有一个称为resultSelector第二个参数的东西。现在在 rxjs v6 中,你可以用 做同样的事情inner map,让我来告诉你。

const original = Observable.of({
    a: this.http.get('https://jsonplaceholder.typicode.com/todos/11'),
    b: this.http.get('https://jsonplaceholder.typicode.com/todos/22'),
    c: this.http.get('https://jsonplaceholder.typicode.com/todos/33')
});

const transformed = original.pipe(
    mergeMap(sourceValue => 
        forkJoin(_.values(sourceValue)).pipe(map(resolvedHttpRequests => {
            // here you have access to sourceValue as well as resolvedHttpRequests so you can do manual join to match the data.
        }))
    )
)
Run Code Online (Sandbox Code Playgroud)

小智 2

2020 年更新

forkJoin(
  // as of RxJS 6.5+ we can use a dictionary of sources
  {
    google: ajax.getJSON('https://api.github.com/users/google'),
    microsoft: ajax.getJSON('https://api.github.com/users/microsoft'),
    users: ajax.getJSON('https://api.github.com/users')
  }
)
  // { google: object, microsoft: object, users: array }
  .subscribe(console.log);
Run Code Online (Sandbox Code Playgroud)

https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin