How Do I Make A New Call To An Api When A Previous One Finished Successfully?
I am new to angular and rxjs, and I have the following scenario, in which I need that after a call to an api is successfully resolved to make a new call, in the context of angular
Solution 1:
I understand you have a serviceOne
and a serviceTwo
. And you want to call serviceTwo
using the retrieved data from serviceOne
.
Using rxjs switchMap you can pipe one observable into another.
handler(): void {
this.serviceOne
.createDirectory(this.path)
.pipe(
switchMap(serviceOneResult => {
// transform data as you wishreturnthis.serviceTwo.methodCall(serviceOneResult);
})
)
.subscribe({
next: serviceTwoResult => {
// here we have the data returned by serviceTwo
},
error: err => {},
});
}
If you don't need to pass the data from serviceOne
to serviceTwo
but you need them to be both completed together, you could use rxjs forkJoin.
handler(): void {
forkJoin([
this.serviceOne.createDirectory(this.path),
this.serviceTwo.methodCall()
])
.subscribe({
next: ([serviceOneResult, serviceTwoResult]) => {
// here we have data returned by both services
},
error: err => {},
});
}
Solution 2:
Using aysnc
and await
you can do:
asynchandler(): void {
awaitthis.serviceNAme
.createDirectory(this.path)
.pipe(
finalize(() => {
this.someProperty = false;
})
)
.subscribe(
(data) =>console.log(data),
(error) =>console.error(error.message)
);
// Do second api call
}
Solution 3:
There are a few says to do this:
Scenario # 1
Your two service api calls are independent, you just want one to go and then the next
const serviceCall1 = this.serviceName.createDirectory(this.path);
const serviceCall2 = this.serviceName.createDirectory(this.otherPath);
concat(serviceCall1 , serviceCall2).subscribe({
next: console.log,
error: err =>console.error(err.message),
complete: () =>console.log("service call 1&2 complete")
});
Scenario # 2
Your two calls dependant on one another, so you need the result of the first before you can start the second
this.serviceName.getDirectoryRoot().pipe(
switchMap(root =>this.serviceName.createDirectoryInRoot(root, this.path))
).subscribe({
next: console.log,
error: err =>console.error(err.message),
complete: () =>console.log("service call 1 used to create service call 2, which is complete")
});
You'll want scenario # 2, because done this way, an error in the first call will mean no result is sent to the switchMap
, and second call is never made.
Post a Comment for "How Do I Make A New Call To An Api When A Previous One Finished Successfully?"