javascript - RxJs consequent observables:如果发生错误则继续执行
问题描述
我需要结合两个 api 调用 -serviceA
和serviceB
. serviceB
应该在之后调用serviceA
。但是,如果serviceA
失败,代码应该继续执行并调用serviceB
.
使用 RxJS 的正确方法是什么?
这是我尝试过的:
this.serviceA.getData(id).pipe(
map((data) => {
return { ...data, test: "abc" };
}),
mergeMap((res) => {
return this.serviceB.getData(id).pipe(
map((scores) => this.handleData(scores)),
catchError(() => of(res))
);
})
);
解决方案
catchError
如果要从服务 A 中捕获错误,则需要将前面的内容放入管道中:
this.serviceA.getData().pipe(
catchError(errA => of(errA)),
map(dataA => ({ ...dataA, test: "abc" })),
switchMap(objA => this.serviceB.getData(objA)),
catchError(errB => of(errB)),
map(dataB => this.handleData(dataB))
);
在上面的代码中,第一个catchError
将捕获调用中发生的错误serviceA.getData()
并返回一个 observableswitchMap
将接收为dataA
. 执行将继续,因此无论是否发生错误,都会调用 serviceB。
第二个catchError
将捕获来自serviceB.getData()
.
这个交互式StackBlitz演示了这种行为。
推荐阅读
- codeigniter-3 - 如何创建 docx 文件并使用 PhpWord 下载它
- javascript - 刷新后 Github 页面 URI 上的客户端路由和 404
- c# - 使用 C# 在 XML 文件中转换 CSV
- python - 熊猫从应用于列的字典返回函数创建列
- reactjs - 如何在ANTD轮播预览中显示情侣图像
- android-studio - 协调器布局占用太多空间:Android Studio 布局
- python - Python - 用于列出列表中数字计数的 For 循环
- javascript - 在 redux saga 请求完成并且数据存在后渲染 visx wordcloud 导致“只读”错误
- php - docker php8.0-apache new relic - 无法加载动态库“newrelic.so”
- javascript - React Native 两次拉取相同的数据