tt0206
tt0206

Reputation: 847

Angular Multiple HTTP Requests with RxJS (NOT rely on each other)

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.

Upvotes: 1

Views: 1344

Answers (1)

user184994
user184994

Reputation: 18281

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

Upvotes: 1

Related Questions