2017-05-12 41 views
0

我正在嘗試使用NodeJS API作爲後端服務器來執行Angular2的登錄表單。POST表單Angular2

我不能發佈任何請求的API。 這是我前面的代碼示例:

private authenticate_url = "Server_URL:PORT/authenticate"; 
login(username: string, password: string): Observable<User> { 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    console.log("Username : "+username+" Password : "+password); 
    return this.http.post(this.authenticate_url, { username, password }, options) 
       .map(this.extractData) 
       .catch(this.handleError) 
} 

既可以當我檢查網絡活動,沒有POST請求被執行。

+0

檢查您的瀏覽器f12,檢查它是什麼日誌記錄。 –

+0

錯誤TypeError:this.http.post(...)。map(...)。catch不是一個函數 –

回答

0

您需要使用RxJS的.subscribe()方法,以實際執行查詢,所以你需要把它寫這樣的:

return this.http.post(this.authenticate_url, { username, password }, options) 
       .map(this.extractData) 
       .catch(this.handleError) 
       .subscribe((queryResult) => {console.log(queryResult)}) 

或者你可以做你的功能之外,如:

login("baksdasd", "asfasfasdf").subscribe((queryResult) => {console.log(queryResult)}) 

您還需要導入您所使用的運營商:

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

在這裏,你有有詳細的d教程解決您可能遇到的任何其他問題:https://scotch.io/tutorials/angular-2-http-requests-with-observables

+0

我不能使用subscribe函數,因爲我使用的是Observable。在這種情況下,我認爲正確的方法是使用「地圖」而不是「訂閱」。 使用你的代碼,我有這個錯誤: 錯誤在/home/iot/ng2-admin/src/app/_services/authentication.service.ts(25,18):屬性'catch'類型'訂閱'。 –

+0

是的,對不起,您需要訂閱Observable。所以如果你在你的函數中返回它,你將需要訂閱你想要使用它的地方,就像我在第二個例子中展示的那樣。我要更新我的答案。 – jesusbotella

+0

我的代碼中缺少的東西是訂閱Observable!我需要的就是那個。謝謝Jesusbotella –