angular - 使用 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()不起作用。
我不确定如何处理这种情况。
解决方案
你可以用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.
});
推荐阅读
- javascript - 异步 Qestiong Node.js
- python - 列表中三元运算符的折叠
- javascript - 在 React 组件中实例化 JavaScript 对象
- .net - 仅组合 64 位时,图标保持默认
- json - 在 json 文件中使用 python argparse 参数作为变量值
- html - 目标特定标签(亚马逊会员)
- git - 如果我对这两个组织都具有权限,则将回购从一个私有 azure devops 组织导入到我的私有组织
- ubuntu-16.04 - 在 Ubuntu 16.04 上创建解决方案文件时,JetBrains Rider 挂起
- php - PHP exec 运行 audtool 的 bash 脚本的网页输出不正确(Audacious 的一部分)
- php - 在 Mac 上使用 XAMPP 安装 XDebug for PHP