angular - 在服务中出现 Angular API 调用错误后向用户显示模板中的错误
问题描述
我将非常感谢一些帮助。当服务内部的 api 调用没有网络连接时,我试图在我的模板中向用户返回错误消息。
很多帮助已经过时了。
我的组件
this.dataService.GetQuotePopCats().subscribe(
popCats => {
this.popCats = popCats['data'];
},
error => {
this.ErrMsg = "A PROBLEM" <<< I want to display this in my template
console.log("ERROR", error); <<< NEVER GETS HERE
}
);
在我的服务中...
GetQuotePopCats() : Observable<any> {
const headers = new HttpHeaders({'No-Auth':'True'})
headers.append('Content-Type', 'application/json')
return this.http.get(this.globals.API_URL + 'GetQuotePopCats/?action=GETPOPCATS', {headers: headers}).pipe(
map((res: any) => res.json()),
catchError(<T>(error: any, result?: T) => {
return of(result as T)
})
)
}
我已经复制了上面的代码,老实说我并没有完全理解它。
解决方案
因为您由of
操作员处理错误
catchError(<T>(error: any, result?: T) => {
return of(result as T)
})
在那种情况下总是会工作
popCats => {
this.popCats = popCats['data'];
},
您需要catchError
从您的请求中删除或替换为
catchError(<T>(error: any, result?: T) => {
return throwError(result as T)
})
推荐阅读
- class - 我的 Parser 类的类型有什么问题?
- javascript - 如何检查数据库中是否存在用户
- ios - 是否有可能有一个能够排除具有初始值的属性的默认结构初始化程序?
- python - "detail": "方法 \"GET\" 不允许。" Django 休息框架
- python - 我可以安全地删除“/anaconda3/pkgs”中的文件吗?
- assembly - 方向 EFLAG 的值如何影响 SCAS 和 MOVS 指令?
- java - 完全相同的逻辑,第一个代码将数据存储为 Map
第二作为地图 . 第一次运行良好。第二个给出 StackOverflow 错误。为什么? - ios - UIPageViewcontrollers,childcontroller 按钮点击事件不起作用
- ios - Swift UIView 自动布局和约束
- java - 如何显示不同数据类型的ArrayList