【发布时间】:2019-02-15 16:10:54
【问题描述】:
有没有办法在 post 方法中更改响应类型(角度 5)在收到响应后?
问题:当响应正常时我需要 responseType成为blob。如果没有 - 我需要 json responseType。
我进行了一些谷歌搜索,但找不到完全适合我情况的答案。
代码示例(简要):
// just simple method in service
export class MyService {
constructor(private http: HttpClient) {}
doSomething(data, fileName): Observable<any> {
return this.http.post('url', data, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'),
params: new HttpParams().set('fileName', fileName),
responseType: 'blob'
})
}
}
// just classic method in component
export class MyComponent {
constructor(private myService: MyService) {}
this.myService.doSomething(this.data, this.file).subscribe(() => {
// here doing something useful
}, (error: HttpErrorResponse) => {
// handling the error
})
}
所以,再一次,在这种情况下,每次我都收到 blob 中的响应,如果一切都很好,那就太好了。但是如果我有错误,我需要在 json 中做出响应。反之亦然。
我如何在这两种情况下都设置正确的 responseType?
提前致谢。
【问题讨论】:
-
在您的服务中使用
.map()运算符 -
您可以在错误处理程序中尝试
JSON.parse(${error.error})吗?
标签: javascript json angular blob response