rxjs switchmap可观察,将变量保存为最终变量

时间:2018-06-27 12:47:40

标签: javascript rxjs

我需要知道这个问题的良好实践。

我正在使用switchMaps调用三个服务concat,但是对于最后一个服务,我需要第一个服务的变量。最佳做法是如何做到的?

示例:

this.session.account.get()
.switchMap(account => this.employerApi.get(account.accountId))
.switchMap(employer => this.addressApi.get(employer.addressId))
.filter(address => address.numer % 2)
.subscribe(address => console.log(¿¿¿¿¿account.name?????, address.name));

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

最简单的方法是随便汇总值:

this.session.account.get()
  .switchMap(account =>
    this.employerApi.get(account.accountId).map(employer => ({employer, account}))
  .switchMap(data => 
    this.addressApi.get(employer.addressId).map(address => ({...data, address}))
  .filter(data => data.address.number % 2)
  .subscribe(...)

答案 1 :(得分:1)

不确定这是最好的方法,但这是一种方法:

this.session.account.get()
.switchMap(account => zip(Observable.from(account), this.employerApi.get(account.accountId))
.switchMap((account, employer) => zip(Observable.from(account), this.addressApi.get(employer.addressId))
.filter((account,address) => address.numer % 2)
.subscribe((account,address) => console.log(¿¿¿¿¿account.name?????, address.name));

但是,就最佳实践而言,我认为您需要的是后端的序列化程序,该序列化程序以json格式返回结果,例如:{ "account": account_object, "address" : address_object}