angular - Angular:无法通过服务捕获 404 API 的消息
问题描述
我想显示 API 返回的状态为 404 的消息,如下所示:
{message: "Email Address does not exists", status: 404, data: null}
这个 API 是用 SpringBoot 语言生成的。
我通过一个service.ts
文件在 Angular 8 中调用 API:
forgotPwd(value, bearer) {
return this.http.put(this.rootUrl + 'api/user/forgot_password', value, {headers: new HttpHeaders({ Authorization: 'Bearer ' + bearer, 'Content-Type': 'application/json'})});
}
在component.ts
文件中,我想处理如下情况:
this.commService.forgotPwd(this.submissionArray, this.userToken).subscribe((data: any) => {
this.rawData = data;
const result = this.rawData;
if (result.status !== 200) {
console.log(result.message);
} else {
console.log(result.message);
}
});
但是,我在控制台中没有看到任何内容。如何在 Angular 中处理 404 / 400 请求,并在上面提到的组件文件中抛出相应的消息?
解决方案
所有的 http 错误都将在错误回调中可用,例如
this.service.getData()
.subscribe(
(data) => {}, // success path
(error: HttpErrorResponse)=> {} // error path
);
在错误中,您将获得状态和消息。
所以对于你的情况,
this.commService.forgotPwd(this.submissionArray, this.userToken)
.subscribe((data: any) => {
this.rawData = data;
const result = this.rawData;
console.log(result.message);
}, error => {
console.log('handle error');
});
注意:当 Rest API 返回 4XX 或 5XX 作为响应状态时,上述场景有效。
推荐阅读
- cakephp - 预期类型“Cake\Datasource\EntityInterface”。找到“应用\模型\表\实体”
- corda - Corda - 无法在证书\sslkeystore.jks 中找到存储
- swift - 从列表中的 NavigationLink 推送新列表会冻结模拟器/画布(SwiftUI)
- amazon-web-services - 使用 CloudWatch 指标过滤器提取 Lambda 持续时间
- java - 如果我知道它的 URL,如何获取图像大小?安卓 (java)
- sql - 将许多大文件从 R 复制到新的 SQL 数据库
- prolog - Prolog 术语:id(X,X)。事实还是规则?
- excel - 使用具有两个条件的 COUNTIFS?
- php - 代码在 PHP 7.3 中无法正常运行。修复与 PHP 7.1 和 7.2 向后兼容的最佳方法,count() 错误
- reactjs - React-admin 表显示两次