'When Updating to HttpClient: Uncaught in Promise/Http Failure during parsing
In my angular app I'm updating from Http to HttpClient, which doesn't seem to work when working with Promises.
It seems like you need to use a little 'work-around' when dealing with promises in the httpClient, I tried to do it like in this article: https://vitalflux.com/angular-promise-explained-code-example/ but to no avail.
I also tried to work with Observable instead (and subscribe in the component.ts), but this also did not work out.
service.ts (with old Http, works like a charm)
public viewPDF(profileId: string, profileVersion: Date): Promise<any> {
const pdfVersion = _.split(_.replace(profileVersion.toISOString(), /:/g, '-'), '.')[0];
return this.http
.get(`${this.pdfApiView}/${profileId}/${pdfVersion}`)
.toPromise()
.then(response => response);
}
service.ts (-- now with HttpClient)
public viewPDF(profileId: string, profileVersion: Date): Promise<any> {
const pdfVersion = _.split(_.replace(profileVersion.toISOString(), /:/g, '-'), '.')[0];
return this.httpClient
.get<any>(`${this.pdfApiView}/${profileId}/${pdfVersion}`)
.toPromise()
.then(response => response);
}
component.ts
this.pdfDocumentService.viewPDF(prof[0].id, prof[0].version).then(resp => {
if (resp._body !== 'file not found') {
this.pdfList.set(prof[0].id + prof[0].version, resp.url);
}
});
The new method lead to the following Error messages:
ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost:4200/api/pdfFile/i1cib1pgvk000000/2019-04-02T12-47-57","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost:4200/api/pdfFile/i1cib1pgvk000000/2019-04-02T12-47-57","error":{"error":{},"text":"%PDF-1.3\n%����\n6 0 obj\n<<\n/Type /Page\n/Parent 1 0 R\n/MediaBox ...
Solution 1:[1]
Thank you, this is what worked:
return this.httpClient.get(`${this.pdfApiView}/${profileId}/${pdfVersion}`, {
observe: 'response',
responseType: 'blob',
});
I also needed to omit the casting (post)
Solution 2:[2]
You don't need to use .then() .toPromise(), just look at this example.
In your service.
getData(): Observable<any> {
let body: any = {};
const options = { responseType: 'blob' };
const url = `your api url`;
return this._http.post<any>( url, body, options );
}
and then consume
this._service.getData().subscribe(res => {
console.log(res)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lukas |
Solution 2 | Agustin Meriles |