2016-03-18 27 views
22

我想將一個REST響應複製到一個blob中,但我無法做一些,因爲blob()arrayBuffer()尚未在響應對象中實現。 Response Body是一個私有變量。如何在不將其轉換爲字符串或json的情況下訪問Angular 2 http響應主體?

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

是否有解決方案,我可以使用,直到這些方法得到實施?

回答

46

還有一個更簡單的解決方案,以訪問身體,我還沒有看到任何相關文檔的字符串:

let body = res.text() 
+3

哇!這個解決方案實際上允許npm編譯我的TS!你甚至在哪裏找到這個? –

+1

有很多涉及試驗和錯誤,所以我不能真正記得我害怕。 – StudioLE

6

由於我在遇到同樣的問題時發現了此問題(並且Angular的文檔沒有像今天那樣更新),您現在可以使用:

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

另一種解決方法,如果你因爲某些原因是在老版本的角度2:

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

設置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; 
     }) 
+0

有關新功能的更多信息:http://restlet.com/company/blog/2016/08/29/whats-new-in-the-http-module-of-angular-2/,不要忘記使用訂閱利用結果 – bleuscyther

8

插件到@StudioLE。你可以使用json()方法以json的形式返回數據。

let body = res.json() 
+1

這絕對是應該使用的。在你的錯誤響應中,你可以執行'error.json()',並且API中實際返回的數據將在模板中可用。 – Rexford

+0

Dangit,我忘了使用'.json()'哈哈感謝這個答案,幸運的是我只是把我的腦袋敲了幾分鐘。 –

相關問題