在RxJS中链接订阅

时间:2018-01-02 17:23:47

标签: javascript rxjs observable

我的服务功能如下:

newGetClient(client_id, token):Observable<Response> {
  let headers = new Headers();
  headers.append("authentication", token );
  let options = new RequestOptions({ headers: headers });

  let final_url = `${this.baseUrl}/${client_id}?model=client`

  return this.http.get(final_url, options)
    .map(this.extractData)
    .catch(this.handleError)
}

我在控制器中调用:

fetchClients() {
  this.clientService.newGetClient(this.client_ids[0], this.auth_token).subscribe( data => {
    this.c1 = this.parseClient(data)
    this.clientService.newGetClient(this.client_ids[1], this.auth_token).subscribe( data => {
      this.c2 = this.parseClient(data)
      this.generateKeys()
    })
  })
}

generateKeys() {
  this.keys = _.union(Object.keys(this.c1), Object.keys(this.c2))
  this.loaded = true
}

但我正在使用2个fetchClients()来调用client_ids,并且一旦完成对fetch的两次调用,我都需要单独调用generateKeys()

我觉得嵌套对newGetClient()的调用是不正确的,所以我想知道如何将它们链接起来,这样我就可以在两个订阅完成后调用generateKeys()

2 个答案:

答案 0 :(得分:3)

由于这两个调用并非相互依赖,因此您可以使用forkJoin()

const o1 = this.clientService.newGetClient(this.client_ids[0], this.auth_token);
const o2 = this.clientService.newGetClient(this.client_ids[1], this.auth_token);

Observable.forkJoin(o1, o2).subscribe(([result1, result2]) => {
  this.c1 = this.parseClient(result1);
  this.c2 = this.parseClient(result2);
  this.generateKeys();
});

如果您希望能够在他们到达时分配c1c2而无需等待两个Observable完成,您可以将o1o2链接到{ {1}}:

do()

答案 1 :(得分:1)

你可以使用zip来组合你的两个可观测量 - 它会在两个可观测量都被发射时发射。

这样的事情(注意:它没有经过测试,但你应该明白这一点):

fetchClients() {
    rx.observable.zip(
        this.clientService.newGetClient(this.client_ids[0], this.auth_token).map(this.parseClient),
        this.clientService.newGetClient(this.client_ids[1], this.auth_token).map(this.parseClient)
    )
    .map(arrClients => _.union(Object.keys(arrClients[0]), Object.keys(arrClients[1])))
    .subscribe( clientUnion => {
        this.keys = clientUnion;
        this.loaded = true
      });
}