前一个成功完成后,如何对api进行新的调用? [英] How do I make a new call to an api when a previous one finished successfully?
问题描述
我是不熟悉angular和rxjs的人,我有以下情形,在这种情况下,我需要在api/rxjs的上下文中成功解决对api的调用以进行新的调用之后,我不知道怎么做
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 / rxjs I don't know how to do it
handler(): void {
this.serviceNAme
.createDirectory(this.path)
.pipe(
finalize(() => {
this.someProperty = false;
})
)
.subscribe(
(data) => console.log(data),
(error) => console.error(error.message)
);
}
上一个成功后,对api进行新调用的正确方法是什么?
What is the correct way to make a new call to an api when a previous one was successful?
推荐答案
我了解您有一个 serviceOne
和一个 serviceTwo
.您想使用从 serviceOne
中检索到的数据调用 serviceTwo
.
I understand you have a serviceOne
and a serviceTwo
. And you want to call serviceTwo
using the retrieved data from serviceOne
.
使用rxjs switchMap ,您可以将一个可观察的管道传输到另一个.
Using rxjs switchMap you can pipe one observable into another.
handler(): void {
this.serviceOne
.createDirectory(this.path)
.pipe(
switchMap(serviceOneResult => {
// transform data as you wish
return this.serviceTwo.methodCall(serviceOneResult);
})
)
.subscribe({
next: serviceTwoResult => {
// here we have the data returned by serviceTwo
},
error: err => {},
});
}
如果您不需要将数据从 serviceOne
传递到 serviceTwo
,但是您需要将它们一起完成,则可以使用rxjs
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 => {},
});
}
这篇关于前一个成功完成后,如何对api进行新的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!