2016-11-03 72 views
3

我有很難理解Angular2 HTTP(可觀察)方法:爲什麼我們需要用戶的方法:Angular2

這裏是我的代碼:

login(username:string,password:string) { 
    let headers = new Headers(); 

    this.createAuthorizationHeader(headers,username,password); 

    return this.http 
     .get(this.url,{headers:headers}) 
     .map(this.extractData) 
     .catch(this.handleError).subscribe(e => console.log(e)); 
} 

private extractData(res: Response) { 
    let body = res.json(); 
    console.log(body); 
    return body.data || { }; 
} 

我的問題是:我們爲什麼需要訂閱方法,如果我們可以提取Observable的地圖方法中的數據和其他所有內容?

謝謝

回答

2

HTTP調用是異步的,這意味着它們不會被調用後立即結束。

subscribe方法,做兩兩件事:

  1. 它開始'該呼叫(在這種情況下,發送該HTTP請求)

  2. 它調用傳遞作爲參數的函數(回調函數)在調用完成後,返回的數據。

1

沒有subscribe()什麼都不會發生。 Observable s是懶惰的,只有在調用subscribe(),toPromise()forEach()時纔會執行它們。

您不需要在subscribe()中做任何事情,只需要調用它即可。

return this.http.get(this.url,{headers:headers}) 
      .map(this.extractData) 
      .catch(this.handleError) 
      .subscribe(e => console.log(e)); 

return this.http.get(this.url,{headers:headers}) 
    .subscribe(this.extractData, this.handleError); 
相關問題