首页 > 解决方案 > 使用 RxJS 的 Angular 多个 HTTP 请求(不相互依赖)

问题描述

Angular 6:使用 RxJS(updatePhone 和 updateAddress)的 Angular 多个 HTTP 请求,它们不相互依赖,但两者可能一起执行,也可能不一起执行。

案例 1:对地址字段(地址、州、城市或邮编)所做的更改,我需要调用 updateAddress api。

案例 2:对电话字段(电话号码或电话类型)所做的更改,我需要调用 updatePhone api。

案例 3:如果地址和电话都变了,我需要更改 updateAddress 和 updatePhone api。

我试过了

import { forkJoin, combineLatest, Observable } from 'rxjs';

let phoneUpdate, addressUpdate;

if (this.isPhoneUpdateApi)
  phoneUpdate = this.customerService.updatePhone(phoneUpdateRequest);
if (this.isAddressUpdateApi)
  addressUpdate = this.customerService.updateAddress(addressUpdateRequest);

  const combined = combineLatest(phoneUpdate, addressUpdate);
  combined.subscribe(
    ([phoneUpdateResponse, addressUpdateResponse]) => {
      console.log(
        `Phone Update Response: ${phoneUpdateResponse.model},
         Address Update Response: ${addressUpdateResponse.model}`
      );
      this.isPhoneUpdateApi = false;
      this.isAddressUpdateApi = false;
      console.log('this.isAddressUpdateApi', this.isAddressUpdateApi, 'this.isPhoneUpdateApi', this.isPhoneUpdateApi);
    });

但是,如果只有电话更改而不是地址更改,则combineLatest()不起作用。

我不确定如何处理这种情况。

标签: angularrxjs

解决方案


你可以用forkJoin这个。

reqs = [];
if (shouldUpdatePhone) {
   reqs.push(this.customerService.updatePhone(phoneUpdateRequest))
}
if (shouldUpdateAddress) {
   reqs.push(this.customerService.updateAddress(addressUpdateRequest))
}

forkJoin(reqs).subscribe(result => {
   // Do whatever you want when they're both done.
});

推荐阅读