![](/img/trans.png)
[英]Getting a Full Response (not just the body) from Angular 4 HTTP Calls
[英]Angular getting response body
我無法理解如何從Angular Response對象獲取響應主體。 在他們的文檔中,他們有一個例子說明
http.request('my-friends.txt').subscribe(response => this.friends = response.text());
然而,當我嘗試做let body: string = response.text();
我得到一個錯誤,說“類型'承諾'的參數不能分配給'string'類型的參數”。
我試着將它視為承諾和行動
let body: string; response.text().then(text => body = text);
這會刪除編譯錯誤,但是當調用此代碼時,它會拋出錯誤,並顯示“TypeError:response.text(...)。然后它不是函數”。
我想了解Promise究竟是什么以及我需要如何檢索它的屬性。
我相信你在導入中引用了錯誤的Response
對象。 如果您要指定類型需要從Angular包導入Response對象:
import { Response } from '@angular/http`;
瀏覽器本身也支持fetch API的Response對象。 它們的不同之處在於Angular Response
對象返回Response.text()
方法的string
,而fetch API Response
返回一個promise。 http
服務使用Angular的Response
對象,它返回一個字符串,這樣你就不需要一個promise。
如果要將正文保存到body
變量,則必須在從observable獲取值時執行此操作:
http.request('my-friends.txt').subscribe((response: Response) => this.body = response.text());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.