我正在尝试从http.get
访问WEB API但它无法正常工作这是我使用observable的服务,但它根本不工作既不调用服务器也不显示任何错误好。
@Injectable()
export class SetupServiceObservables {
public apiServiceBaseUri = 'http://localhost:3000/';
private authheaders: any = {};
private config: any = {};
private auth: any = {};
constructor(private http: Http, private ngWEBAPISettings: WebAPISettings, private authService: AuthService, private router: Router) {
}
public get(servicename: string): Observable<any> {
return this.http.get(this.ngWEBAPISettings.apiServiceBaseUri + "api/" + servicename + "/", this.getConfig())
.map(this.extractData)
.catch(this.handleError);;
}
public getConfig() {
this.authheaders.Authorization = this.auth.access_token == "" ? "" : 'Bearer ' + this.auth.access_token;
this.config = {
headers: {
'Authorization': this.authheaders.Authorization
},
cache: false,
};
return this.config;
}
private extractData(res: Response) {
let body = res.json();
console.log(res);
return body.data || {};
}
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);
}
}
答案 0 :(得分:1)
Observable很冷,所以你必须致电subscribe
示例服务实现如下所示 -
getEmployees(): Observable<{}> {
return this._http.get(this._webApiUrl)
.map((response: Response) => <any[]> response.json())
.catch(this.handleError)
;
}
您可以从您的组件订阅 -
this._webApiService.getEmployees().subscribe(
emplist => this.employees = emplist,
error => this.errorMessage = <any>error
);
看看这是否有帮助。