angular - rxjs:如何从 catchError 中返回另一个 observable 的结果
问题描述
我正在使用 rxjs 6.5 和 angular。基本上,我想在我的服务中有一个方法:
- 如果 api 响应,则从第一个 api 调用返回状态
- 如果第一个调用失败,则返回第二个(不同的)api 调用的状态
- 如果第二次调用失败,则返回一个虚拟值
这是我到目前为止所拥有的。我想我需要使用flatMap/mergeMap
,但我不知道如何使用。
服务.ts
public getStatus()
{
return this.http.get('http://api.com/status1')
.pipe(
catchError(() => {
//makes 2nd api call here
return this.http.get('http://api.com/status2')
.pipe(catchError(() =>
{
//both calls failed
return of({
data: 'blah',
success: false
});
}))
}));
}
组件.ts
this.service.getStatus().subscribe(status=>this.status = status);
有人可以帮忙吗?
解决方案
您的方法有效,但嵌套管道看起来不太好。不过,您可以做一件简单的事情:
// Use 'of' operator to "fake" a successful API call.
// Use 'throwError' operator to "fake" a failed API call.
public getStatus()
{
return of('firstApiCall')
.pipe(
catchError(() => {
//makes 2nd api call here
return of('secondApiCall')
}),
catchError(() =>
{
//both calls failed
return of({
data: 'blah',
success: false
});
})
);
}
您可以提取第二个catchError
块以将所有运算符放在一个级别上 -catchError
运算符只会在可观察对象引发错误时触发,并且由于您希望对每个调用进行不同的错误处理,因此可以这样做。
可能你也可以只用一个块来处理它,catchError
并对请求 URL 进行一些检查以确定你想要返回什么,但我想这需要更多的逻辑并且不值得。
请查看提供的 stackblitz 以查看实际情况:
推荐阅读
- c++ - 如何从向量中删除唯一的ptr
- sql - 如何在 BigQuery 中创建可重用的 UDF
- javascript - sessionStorage 在 Microsoft Edge 中不起作用
- asp.net - 使用 jquery datepicker 从数据库中获取假期
- sql - 仅按人名过滤
- python - 是否可以从邻接列表中找到每个节点中传入边的序列?
- groovy - Jmeter:Groovy:从 Windows 运行时显示运行 groovy 脚本时出错,但在 mac 中运行良好
- java - Spring Boot 应用程序未在 openWRT 上运行
- oracle - 连接到通过同一端口侦听的同一台计算机上的数据库时出现 ORA-12505 错误
- r - 显示实际删除的空日期的绘图