[英]How to make HTTP POST call in Angular2 and print the response
我是Angular2的新手並且正在建立一個示例項目來學習它。 我正在尋找如何在Angular2中進行HTTP調用並找到此代碼段示例:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://www.syntaxsuccess.com/poc-post/',
JSON.stringify({firstName:'Joe',lastName:'Smith'}),
{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);
我不確定訂閱的作用,但我的主要目標是打印響應。 從這段代碼我可以看到響應,但我不確定如何“隔離和訪問它”(我希望這是有道理的)。 我的問題是如何將響應打印到控制台?
我的問題是如何將響應打印到控制台?
你可以打印res
:
.subscribe((res:Person) => { this.postResponse = res; console.log(res); });
我不確定訂閱的作用(...)
Http.post(...)
(link)的結果是一個Observable<Response>
(鏈接) 。
在您的代碼中,您選擇POST的結果(一個Observable<Response>
)並在其上調用.map()
(鏈接) 。 在您的情況下,您這樣做是為了將響應解析為JSON並將其轉換為對象:
.map((res: Response) => res.json())
現在, .map()
的結果也是一個Observable<Response>
。 那是你打電話subscribe
的時候。
subscribe()
(link)是Observable
(link)類的一個方法,它允許你,“注冊”或“訂閱”三個函數來處理/讀取這個可觀察的發出的結果(或“事件”) - 它們被稱為( on ) next
,( on ) error
和( on ) complete
。
因此,使用.subscribe()
的代碼通常是:
.subscribe(
(response) => {
/* this function is executed every time there's a new output */
console.log("VALUE RECEIVED: "+response);
},
(err) => {
/* this function is executed when there's an ERROR */
console.log("ERROR: "+err);
},
() => {
/* this function is executed when the observable ends (completes) its stream */
console.log("COMPLETED");
}
);
所以,為了完全理解Angular2的Http,我建議你閱讀一些關於RxJS和Observables的資源。 當你從它回來時,事情將變得更加簡單,我保證(沒有雙關語:)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.