angular - 如何处理使用 observables 填充选择选项的 http 代码错误
问题描述
我通过调用 Web 服务来填充一些可观察的选项。关键是我试图获取 http 代码错误以隐藏表单(如果其中任何一个 http 代码与 200 不同)并向用户显示消息。
有人可以建议我这样做的好习惯吗?
提前致谢!
回购:https ://github.com/jreategui07/testing-subscriptions-form
模拟服务器运行: mockserver -p 8080 -m mock
GET.mock
HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: *
Content-Type: text/plain; charset=utf-8
Connection: keep-alive
[
{ "error": "c1", "error_des": "any error" }
]
解决方案
为了将来参考,请尝试在此处粘贴相关代码,以便其他用户可以看到您要执行的操作。您的相关代码是您的 catalogue.service.ts:
export class CatalogueService {
requestOptions: any;
constructor(public http: HttpClient) {
const headers = new HttpHeaders({
'Content-Type': 'text/plain; charset=utf-8'
});
this.requestOptions = { headers: headers, observe: 'response' };
}
getColors() {
return this.http.get('http://localhost:8080/getColors', this.requestOptions).pipe(map(response => response['body']));
}
getBrands() {
return this.http.get('http://localhost:8080/getBrands', this.requestOptions).pipe(map(response => response['body']));
}
getSizes() {
return this.http.get('http://localhost:8080/getSizes', this.requestOptions).pipe(map(response => response['body']));
}
getFruits() {
return this.http.get('http://localhost:8080/getFruits', this.requestOptions).pipe(map(response => response['body']));
}
}
特别是,由于您已经正确观察到response
,您可以简单地检查哪个是响应类型:
this.http.get('http://localhost:8080/getColors', this.requestOptions)
.pipe(
map(response => !response.ok ?
throw new Error('Request error, reponse code: ' + response.status :
response['body'])
);
请注意,在 a 中抛出 Errormap
会导致 observable 出错,因此您可以在调用请求的代码上处理它,如下所示:
this.service.getColors().pipe(
catchError((error) => /* do something with that error */
);
尽管如此,您确实要求提供处理此问题的最佳实践。在这种情况下,如果您想以类似的方式处理所有 Http 响应(例如在某处记录它们,或显示通知用户请求失败的工具提示等),我建议您查看Http 拦截器。拦截器使您能够对从模块/应用程序内调用的所有响应创建模块范围甚至应用程序范围的行为。
推荐阅读
- java - 反序列化空值时如何让杰克逊库使用我的默认初始化值?
- visual-studio-2017 - 如何更改 Visual Studio 2017 中的 Microsoft Dynamic 365 X++ 类模板?
- javascript - Laravel Livewire 和 Jodit 所见即所得 HTML 编辑器
- python - 使用 Python 仅从 Cloud Big Table 中获取行键?
- javascript - 在轮播中不显示图像反应
- java - 可以通过在springboot中动态提供表名作为输入来获取列名和表数据
- node.js - 带有 Express 的 WebSocket - 无效的 WebSocket 帧:无效的 UTF-8 序列
- r - R-highcharter 组合工具提示
- javascript - React 聊天应用程序文本是长错误问题?
- c# - 在 MassTransit 中,是否可以拥有包含通用列表的合同的消费者?