VadimB
VadimB

Reputation: 5711

Access error response data when ResponseContentType.Blob is used

I'm facing issue with making request of type ResponseContentType.Blob and getting error message in case of failed call.

The code is pretty simple:

 let headers = new Headers({'Content-Type': 'application/json'});
 let options = new RequestOptions({headers: headers, responseType: ResponseContentType.Blob});

 return this.http.post('url', data, options)
      .subscribe(res => ..., err => console.log(err.json()) /* the problem is here */);

So having fully clarify JSON as server response in case of error but I can't access it: err.json() returns Blob {size: 194, type: "application/json"} only data.

How to access response data? I can't change ResponseContentTypeto smth else as I expect file in case of success request.

Upvotes: 0

Views: 4154

Answers (3)

Hailemichael Adefrs
Hailemichael Adefrs

Reputation: 1

I have faced the same issue: Here you can check my solution

(err) => { err.text().then((value) => console.log(value)); }

Upvotes: 0

Andreas
Andreas

Reputation: 346

You can convert the blob back to text using a FileReader. Then, you can convert the text back to json using JSON.parse().

err => {
  const fr = new FileReader();
  fr.onloadend = (e => {
                     const errorObj=JSON.parse(fr.result);
                     console.log(errorObj);
                 });
  fr.readAsText(err.blob(), 'utf-8');
}

Upvotes: 2

Max Koretskyi
Max Koretskyi

Reputation: 105537

You can just use .blob() method:

err.blob()

The Body class that is implemented by Response class has the following reponse content accessors:

export abstract class Body {
    json(): any
    text(encodingHint: 'legacy'|'iso-8859' = 'legacy'): string
    arrayBuffer(): ArrayBuffer
    blob(): Blob

Upvotes: -1

Related Questions