24

I would like to copy a REST response into a blob but I am unable to do some because blob() and arrayBuffer() have not yet been implemented in the Response Object. The Response Body is a private variable.

...
return this.http.get(url, {params: params, headers: headers})
     .map(res => {   
        // can't access _body because it is private
        // no method appears to exist to get to the _body without modification             
        new Blob([res._body], {type: res.headers.get('Content-Type')});
     })
     .catch(this.log);
...

Is there a solution I can use until these methods get implemented?

sschueller
  • 533
  • 1
  • 6
  • 18

5 Answers5

49

There's a much simpler solution to accessing the body as a string which I haven't seen documented anywhere:

let body = res.text()
StudioLE
  • 656
  • 8
  • 13
10

Addon to @StudioLE. You may use json() method to return data as json.

let body = res.json()
SKL
  • 1,243
  • 4
  • 32
  • 53
  • 1
    This is absolutely what should be used. On your `error` response, you could do `error.json()` and the actually returned data from the API will be available in template. – KhoPhi Aug 15 '17 at 12:55
  • Dangit, I had forgot to use `.json()` lol thanks for this answer luckily I was only banging my head for a few minutes. – Eric Bishard Sep 17 '17 at 09:28
6

Since I found this question while running into the same problem (and Angular's documentation is not updated as of today) you can now use:

let blob = new Blob([response.arrayBuffer()], { type: contentType });

Another workaround if you for some reason are on an old version of Angular 2 is:

let blob = new Blob([(<any> response)._body], { type: contentType });
dmungin
  • 813
  • 6
  • 16
2

set the responseType of requestoptions. That will make the response.blob() method work.

let headers = this.getAuthorizationHeader();
headers.append("Accept", "application/octet-stream");
return this.http
    .get(url, new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob }))
    .map((res: Response): Blob => {
        return res.ok ? res.blob() : undefined;
    });
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
Andreas
  • 31
  • 1
  • more info on the new features : http://restlet.com/company/blog/2016/08/29/whats-new-in-the-http-module-of-angular-2/, dont forget to use subscribe to exploit the result – Jeffrey Nicholson Carré Jun 16 '17 at 23:46
1

I can't see no other solutions before the following PR is merged:

Whereas you have a compilation error, the field can be used at runtime...

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360