如何在不将其转换为字符串或json的情况下访问Angular 2 http响应主体?

ssc*_*ler 23 rest blob httpresponse angular2-http angular

我想复制一个REST响应成团块,但我不能做一些,因为blob()arrayBuffer()尚未响应对象已经实施.Response Body是一个私有变量.

...
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);
...
Run Code Online (Sandbox Code Playgroud)

在实施这些方法之前,我是否可以使用解决方案?

Stu*_*oLE 48

有一个更简单的解决方案来访问身体作为一个字符串,我没有看到记录在任何地方:

let body = res.text()
Run Code Online (Sandbox Code Playgroud)

  • 哇!这个解决方案实际上允许npm编译我的TS!你甚至在哪里找到这个? (4认同)

SKL*_*SKL 10

加入@StudioLE.您可以使用json()方法将数据作为json返回.

let body = res.json()
Run Code Online (Sandbox Code Playgroud)


dmu*_*gin 6

由于我在遇到同样的问题时发现了这个问题(并且Angular的文档在今天没有更新),您现在可以使用:

let blob = new Blob([response.arrayBuffer()], { type: contentType });
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因你在Angular 2的旧版本上的另一个解决方法是:

let blob = new Blob([(<any> response)._body], { type: contentType });
Run Code Online (Sandbox Code Playgroud)