如何在Angular中使用RxJS重写Promise.All(promise1.then(),promise2)

时间:2018-02-19 12:48:35

标签: angular promise rxjs

我有这段代码:

this.account = await this.backend.getAccountInfo();
this.personInfo = await this.backend.getPersonInfo(account.userName);
this.config = await this.backend.getConfig();
this.loaded = true;

现在我想与account和personInfo并行获取配置,所以我使用promises重写了它:

var p1 = this.backend.getAccountInfo()
    .then(account => this.account = account, handleError("account"));

var p2 = p1.then(account => this.backend.getPersonInfo(account.userName))
    .then(personInfo => this.personInfo = personInfo, handleError("current person");

var p3 = this.backend.getConfig()
    .then(config => this.config = config, handleError("config");

await Promise.All(p1, p2, p3);
initialized = true;

如何使用RxJS重写它,假设后端使用HttpClient并返回Observable?

1 个答案:

答案 0 :(得分:0)

您有三个请求,其中第二个请求取决于第一个请求。第三个是独立的,所以你可以做到

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