angular - 如何根据Angular 8中的状态码转换响应体
问题描述
api 根据文件大小返回 2 个状态码。对于 200,它返回一个我已使用 transformImportCSVResponse() 转换为 Object 的 json 字符串。对于 201,它返回一个文本作为响应(“文件上传正在进行中”)
现在它对于 201 失败,因为它无法转换为 json
如何根据状态码处理两者。
this.httpClient.post(url, uploadedFile, {params: httpParams}).pipe(
catchError(err => throwError(err)))
.pipe(map(this.transformImportCSVResponse))
解决方案
问题是 200 和 201,实际上所有 2XX 响应都没有被视为错误。所以你可以做的是:
http
.post<T>('/yoururl', whateverYourPostRequestIs, {observe: 'response'})
.subscribe(resp => {
console.log(resp);
});
代码取自:How can get HttpClient Status Code in Angular 4
然后做if(resp.status === 200) { do thomething }
试试这个代码:
this.http.post(url, uploadedFile, {params: new HttpParams(), observe: 'response'})
.subscribe(
resp => {
if (resp.status === 200) {
this.transformImportCSVResponse(resp.body);
}
},
error => console.log('oops', error)
);
推荐阅读
- reactjs - 如何通过参数覆盖 Material UI 类
- spring - Spring Boot中的异常传播-微服务
- javascript - 卡片翻转 CSS 的问题
- azure - Azure Powershell 诊断设置
- django - Django 继承模型:“无法将关键字 'keyword' 解析为字段。” (Django 2.1.1)
- python - Django CSV 导出选择显示
- r - GLMM中的置信区间
- random-forest - h2o DRF 中权重列的影响
- c# - 如何将额外的 Azure Blob 存储输出添加到 ImageResizer functionapp?
- c# - WPF:在应用 ScaleTransform 时换行文本