Is there a way to change response type in post method (angular 5) AFTER receiving response?
The issue: when the response is okay I need responseType to be blob . If not - I need the json responseType.
I've done some googling around but was unable to find the answer that fully suit my situation.
Code sample (briefly):
// 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
})
}
So, one more time, in that case everytime I get the response in blob and it's great if all is fine. But if I've got error I need response to be in json. And vice versa.
How can I set correct responseType in both situations? Thanks in advance.
I believe you can do this:
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;
}
})
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.