我有多个REST请求要做。请求应该以声明的顺序发生-一个接一个结束。
在所有这些操作的最后,我需要执行一个操作。
我怎么才能做到这一点?我认为一定有比级联请求更好的方法。但我在RxJS和异步编程方面做得很差。
this.http.get <any> ("/a").subscribe ((resp) => { foo ();
this.http.get <any> ("/b").subscribe ((resp) => { bar ();
this.http.get <any> ("/c").subscribe ((resp) => { baz (); }}}
);
// action now发布于 2021-02-22 05:36:42
在这种情况下,我将使用concatMap。
代码将如下所示
this.http.get <any> ("/a").pipe(
concatMap(respA => {
foo();
return this.http.get <any> ("/b");
}),
concatMap(respB => {
bar();
return this.http.get <any> ("/c");
})
).subscribe(
respC => {
baz();
}
);concatMap确保调用的执行按顺序进行。
您可以在常见的http相关用例in this article.中找到如何使用rxJs的灵感。
发布于 2021-02-22 05:23:09
为此,请使用forkJoin
import { forkJoin } from 'rxjs';
并像这样使用它
forkJoin([this.http.get("/a"), this.http.get("/b"), this.http.get("/c")]).subscribe(([respA, respB, respC]) => {});forkJoin函数的输入必须是一个可观察数组。
编辑:
在阅读了@Picci的文章后,我建议使用concat运算符。您可以将副作用放入每个可观察对象的tap操作符中,并仍然将可观察对象数组传递给concat,以保持顺序。
const a$ = this.http.get("/a").pipe(tap(() => foo()));
const b$ = this.http.get("/b").pipe(tap(() => bar()));
const c$ = this.http.get("/c").pipe(tap(() => baz()));
concat([a$, b$, c$]).subscribe(([respA, respB, respC]) => {});
// if you want to handle http errors, you can do it like this
const a$ = this.http.get("/a").pipe(
tap(() => foo()),
catchError((err) => {
handleErr(err);
return of(EMPTY);
})
);https://stackoverflow.com/questions/66306772
复制相似问题