1

Angular 6 : Angular Multiple HTTP Requests with RxJS (updatePhone and updateAddress) that NOT rely on each other but both may or may not execute together.

case 1: Changes made to Address fields (address, state, city or zip), I require to call updateAddress api.

case 2: Changes made to Phone fields (phoneNumber or phoneType), i require to call updatePhone api.

case 3: If both address and phone got change, i require to change updateAddress & updatePhone api.

I tried

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);
    });

But here combineLatest() is not working if only Phone changes and NOT Address change.

I am not sure how to handle this situation.

tt0206
  • 747
  • 3
  • 9
  • 24

1 Answers1

1

You can use forkJoin for this.

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.
});
user184994
  • 17,791
  • 1
  • 46
  • 52
  • I have question on error handling with this approach. i have added new question https://stackoverflow.com/questions/51993575/angular-6-error-handling-with-forkjoin – tt0206 Aug 23 '18 at 20:09