2017-03-02 165 views
1

我有一個調用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)是未定義的。這一定是我猜的時間問題?

回答

1

是的,這是計時問題。 console.log(this.message);語句在響應從您的http請求到達之前得到執行。您應該在訂閱內寫入日誌語句,如下所示。

let response = this.workRequestService.SaveWorkRequest(this.workRequest) 
    .subscribe(
     hero => 
     { 
      this.message = hero; 
      console.log(this.message); 
     }, 
     error => this.errorMessage = <any>error); 
0

試試這個:

ngOnInit() { 
    this.getMessage().subscribe(_ => { 
     console.log(this.message) 
    }); 
} 

public getMessage() { 
    return this.workRequestService.SaveWorkRequest(this.workRequest) 
    .map(hero => this.message = hero,error => this.errorMessage = <any>error); 
0

Observable是異步的。如果您嘗試console.log(this.message);,您將收到未定義的值,直到訂閱值爲止。

在模板上,只需添加{{ this.message?.some_property }}如果您關心的錯誤可能會出來。