How can I get access to the Angular 2 http response body without converting it to string or json?

ⅰ亾dé卋堺 提交于 2019-12-04 15:32:16

问题


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?


回答1:


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

let body = res.text()



回答2:


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

let body = res.json()



回答3:


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 });



回答4:


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;
    });



回答5:


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

  • https://github.com/angular/angular/pull/7260

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



来源:https://stackoverflow.com/questions/36087145/how-can-i-get-access-to-the-angular-2-http-response-body-without-converting-it-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!