我很難確定我的代碼出了什麼問題。我正在嘗試創建一個服務類來連接到我的單獨的數據庫應用程序,該應用程序公開了一個開放的(不安全的)REST API。Angular2 Http - 沒有錯誤,沒有連接
如果我連接到我的瀏覽器中的地址,我可以正確地看到結果,並在我的服務器上記錄連接。但是,當我嘗試通過我的Angular2服務類進行連接時,我在服務器上沒有發生錯誤和連接嘗試。
我一直在重寫下面的內容,閱讀文檔並無法弄清楚!我正在使用2.0.1。
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class AuthenticationService {
private loggedIn = false;
private loginUrl = 'http://localhost:3000/api/users';
constructor(private http: Http) { }
login(user:any): Observable<any[]> {
var x = this.http.get(this.loginUrl)
.map(this.extractData)
.catch(this.handleError);
console.log(x);
console.log("Sent?");
return null;
}
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
}
在我的控制檯我看到控制檯(x)和控制檯的結果(「送?」),所以我知道正在執行的代碼。
您是否在app.module或main.module文件中注入了'HttpModule'? – micronyks
你可以使用'return x;'而不是'return null;'在組件中你可以訂閱登錄方法... – micronyks