javascript - 如何获得失败 api 的响应
问题描述
在我的 api 中,有一些验证失败,并在我的网络选项卡响应中给我错误,如下所示:
{"Message":"not allowed '<' word;"}
但我无法在订阅方法的错误块中显示它。当 api 失败或响应状态代码为 400 时,我如何在我的 toastr 上显示这个。我试过这个:
this.myService
.saveData(myData)
.pipe(takeUntil(this.unsubscribe))
.subscribe(
data => {
this.alertService.success('Record Saved Successfully');
},
error => {
this.spinner.hide();
this.alertService.error(error.Message);
}
);
}
private handleError(error: HttpErrorResponse, scope) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError(
'Something bad happened, please try again later.');
}
解决方案
根据角度文档,这种更改应该有效。
创建自定义错误处理程序或使用默认值
private handleError(error: HttpErrorResponse, scope) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError(
'Something bad happened, please try again later.');
}
然后导入并使用:
import { catchError } from ...
...
...
this.myService
.saveData(myData)
.pipe(takeUntil(this.unsubscribe))
.pipe(catchError(this.handleError)).
.subscribe(
data => {
this.alertService.success('Record Saved Successfully');
}
);
}
推荐阅读
- javascript - 当我使用拖放时,拖动对象部署在 img 内部而不是 div
- coldfusion - 如何在 ColdFusion 中实现 recaptcha v3?
- python - 与 python 的连接问题:badstatusline
- python - UFC 数据集 InvalidArgumentError 断言失败:[Label IDs must < n_classes] [Condition x < y did not hold element-wise:]
- python - 未给出可选参数时在 argparse 中运行钩子的简单方法
- python - 如何将 for 循环转换为向量并将其写入 csv?
- java - 导航到网页中的每个链接后,如何使用 selenium java 使用方法 =post 获取所有表单的列表
- python-3.x - 从 python 执行的 Outlook 邮件模板中删除签名
- python - 无法通过批处理文件运行 pandas python 脚本
- python-3.x - 在 flasgger 中包含外部 yml 文件