我在一个服务中有 2 个 API 调用,每个调用都返回一个 Observable,在我的组件中我有一些条件,如果为真,我必须调用这两个函数,但我需要等待 get() 调用,所以我可以使用 get 调用返回的参数执行 post 函数。如果为 false,我只想使用已定义的参数调用 post 函数。
服务:
get(id: string) {
return this.http.get<any>('get path');
}
post(data: data) {
return this.http.post<any>('post path', {data: data});
}
组件:
execute() {
if (condition) {
this.service.get(id).subscribe( (res) =>
// ...
this.data = res.data;
post(data).subscribe(() => // do stuff...);
);
} else { post(data).subscribe(() => // do stuff...); }
}
我不想为 post 调用重复代码,或者如果根本不可能,只是不要在另一个 subscribe() 中使用 subscribe()。我怎样才能做到这一点?没有异步等待。
提前致谢
最佳答案
您可以使用 RxJS switchMap
运算符从一个 observable 映射到另一个(在你的例子中是 GET 到 POST)并使用 RxJS iif
有条件地返回可观察对象的函数。
尝试以下操作
execute() {
const getPost$ = this.service.get(id).pipe(
switchMap((res: any) => {
this.data = res.data;
return this.service.post(data);
})
);
iif(
() => condition,
getPost$,
this.service.post(data)
).subscribe(
(res: any) => {
// handle response
},
(error: any) => {
// handle error
}
);
}
关于angular - rxjs - Angular : How to wait for an Observable function, 调用另一个返回 Observable 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67385195/