您有三个请求,其中第二个请求取决于第一个请求。第三个是独立的,所以你可以
Rx.Observable.forkJoin(
this.backend.getAccountInfo()
.switchMap(account => this.backend.getPersonInfo(account.userName)
.map(personInfo => [account, personInfo])
),
this.backend.getConfig()
)
.subscribe(([[account, personInfo], config]) => {
this.account = account;
this.personInfo = personInfo;
this.config = config;
this.loaded = true;
});
但那只是
一
这样做的方式。例如,这里有另一种使用副作用的方法:
Rx.Observable.forkJoin(
this.backend.getAccountInfo()
.do(account => this.account = account, () => handleError("account"))
.switchMap(account => this.backend.getPersonInfo(account.userName))
.do(personInfo => this.personInfo = personInfo, () => handleError("current person"))
),
this.backend.getConfig()
.do(config => this.config = config, () => handleError("config"))
)
.subscribe(() => this.loaded = true);
你应该知道
forkJoin
处理错误并添加
catch
您认为合适的运算符。另请注意,第二个版本将分配
this.account
即使
personInfo
然后请求失败。