Angular 6 : How to identify response of api with forkJoin
reqs = [];
if (shouldUpdatePhone) {
reqs.push(this.customerService.updatePhone(phoneUpdateRequest))
}
if (shouldUpdateAddress) {
reqs.push(this.customerService.updateAddress(addressUpdateRequest))
}
forkJoin(reqs).subscribe(result => {
console.log('result :', result);
//How to know response is from updatePhone and response from updateAddress?
});
How to can i identify response received is belong to updatePhone and updateAddress? based on identification i need to show message to user.
this both api returning Array(2) >
{model:true, code:200, message:null},
{model:true, code:200, message:null}
Yes it will be in the same order. The documentations says following : "forkJoin will wait for all passed Observables to complete and then it will emit an array with last values from corresponding Observables.
forkJoin accepts a variable number of observables and subscribes to them in parallel. When all of the provided observables complete, forkJoin collects the last emitted value from each and emits them as an array (this is by default, more on this later).
The forkJoin will subscribe to the passed observables, by making the HTTP GET requests. If any input observable errors at some point, forkJoin will find the error as well and all other observables will be immediately unsubscribed.
ForkJoin method signature has changed This is now deprecated and you must pass an array of observables to forkJoin operator.
You can wrap your reponses in another object that identifies their type by using the map
pipe after each request. Just like this:
reqs = [];
if (shouldUpdatePhone) {
reqs.push(this.customerService.updatePhone(phoneUpdateRequest)
.pipe(map(value => ({type: 'phone', value: value})))
.pipe(catchError(value => of({type: 'phone', failed: true}))))
}
if (shouldUpdateAddress) {
reqs.push(this.customerService.updateAddress(addressUpdateRequest)
.pipe(map(value => ({type: 'address', value: value})))
.pipe(catchError(value => of({type: 'address', failed: true}))))
}
forkJoin(reqs).subscribe(results => {
console.log('result :', results);
for(let result of results){
if(result.type == 'phone'){
if(result.failed)
console.log("Phone failed");
else
console.log("Phone: " + result.value);
}
else if(result.type == 'address'){
if(result.failed)
console.log("Address failed");
else
console.log("Address: " + result.value);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With