有没有办法在收到响应后更改 post 方法中的响应类型(angular 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?
提前致谢。
最佳答案
我相信你能做到:
this.http.post('url', data,
{
observe: 'response',
responseType: 'arraybuffer' ,
headers: new HttpHeaders().set('Accept', 'application/octet-stream; application/json'),
params: new HttpParams().set('fileName', '')
})
.pipe(
map(res => {
if (res.ok) {
const blob:Blob = new Blob([res.body], {type: 'application/octet-stream'});
return blob;
}
else {
var decodedString = String.fromCharCode.apply(null, new Uint8Array(res.body));
var obj = JSON.parse(decodedString);
return obj;
}
})
);
关于javascript - 收到响应后更改 Angular (5)中的响应类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52271107/