【问题标题】:How can I get access to the Angular 2 http response body without converting it to string or json?如何在不将其转换为字符串或 json 的情况下访问 Angular 2 http 响应正文?
【发布时间】:2016-07-05 08:54:07
【问题描述】:

我想将 REST 响应复制到 blob 中,但我无法执行某些操作,因为 blob()arrayBuffer() 尚未在响应对象中实现。响应正文是一个私有变量。

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

在这些方法实施之前,我有什么可以使用的解决方案吗?

【问题讨论】:

    标签: rest angular blob httpresponse angular2-http


    【解决方案1】:

    有一个更简单的解决方案可以将正文作为字符串访问,我在任何地方都没有看到记录:

    let body = res.text()
    

    【讨论】:

    • 哇!这个解决方案实际上也允许 npm 编译我的 TS!你在哪里找到这个?
    • 这涉及到很多试验和错误,所以我真的想不起来了。
    【解决方案2】:

    添加到@StudioLE。您可以使用 json() 方法以 json 格式返回数据。

    let body = res.json()
    

    【讨论】:

    • 这绝对是应该使用的。在您的 error 响应中,您可以执行 error.json() 并且从 API 实际返回的数据将在模板中可用。
    • Dangit,我忘了使用.json() 哈哈感谢这个答案幸运的是我只是敲了几分钟。
    【解决方案3】:

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

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

    如果您出于某种原因使用的是旧版本的 Angular 2,另一种解决方法是:

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

    【讨论】:

      【解决方案4】:

      设置requestoptions的responseType。这将使 response.blob() 方法起作用。

      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】:

      在合并以下 PR 之前看不到其他解决方案:

      虽然您有编译错误,但该字段可以在运行时使用...

      【讨论】:

        猜你喜欢
        • 2017-09-09
        • 2011-04-28
        • 2020-07-01
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        • 2020-04-17
        • 1970-01-01
        相关资源
        最近更新 更多