我有一個調用HTTP觀察到Angular2 HTTP觀察到
SaveWorkRequest(workRequest: any) {
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
let url = 'deployment/SaveWorkRequest';
let dto = { 'workResponse': workRequest };
// post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
return this.http.post(GlobalVariables.SITE_ROOT + url, dto, options)
//.toPromise()
//.then(this.extractData) //...and calling .json() on the response to return data
.map(this.extractData)
.catch(this.handleError);
}
//
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body || {};
}
而這種代碼在調用它的組件下面的方法
let response = this.workRequestService.SaveWorkRequest(this.workRequest)
.subscribe(
hero => this.message = hero,
error => this.errorMessage = <any>error);
console.log(this.message);
的問題是,在該組件返回的代碼之前服務方法。所以console.log(this.message)是未定義的。這一定是我猜的時間問題?