【发布时间】:2018-08-23 23:51:27
【问题描述】:
Angular 6:使用 RxJS(updatePhone 和 updateAddress)的 Angular 多个 HTTP 请求不相互依赖,但两者可能会或可能不会一起执行。
案例 1: 更改地址字段(地址、州、城市或邮编),我需要调用 updateAddress api。
案例 2: 更改电话字段(phoneNumber 或 phoneType),我需要调用 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,这样它们可以同时执行 -
forkJoin 当所有的 observables 完成后,从每个 observables 发出最后一个发出的值。但我有一种情况,我可能不会调用一个 api。手机换了地址却没有的情况。
-
就是这样。这对你有用吗?
-
forkJoin(phoneUpdate, addressUpdate, (phoneUpdateResponse, addressUpdateResponse) => { return { phoneUpdateResponse, addressUpdateResponse }; });
-
我试过上面的代码,但它不起作用。