2017-06-06 40 views
0

我嘗試將響應從打字服務組件中的http.post調用傳遞給angular2組件,以便我可以在前端顯示它們。以下是我的service.ts和component.ts代碼結構。傳遞來自http.post的響應到component.ts in angular2

getSearchProfileResponse(body) { 
    let headers = new Headers({'Content-Type': 'application/json'}); 
    let options = new RequestOptions({headers: headers}); 
    return this.http.post(this._url, body, options) 
     .map((response:Response) => { 
     console.log(JSON.stringify(response)); 
     JSON.stringify(response); 
     }) 
     .catch((error) => { 
     console.log("error is "+ error); 
     return Observable.throw(error); 
     }); 
    } 

getProfile() { 
    this.spinnerService.show(); 
    this.searchProfileRequest = _.cloneDeep(this.searchKey); 
    this.searchProfileService.getSearchProfileResponse(this.searchProfileRequest) 
     .subscribe(
     searchProfileResponse => { 
      this.searchResult = searchProfileResponse; 
      console.log("response in component is "+ searchProfileResponse); // this is displayed as undefined 
      console.log("search result is "+ this.searchResult); 
      this.spinnerService.hide(); 
      this.showProfiles(this.searchResult); 
     }, 
     error => { 
      console.log(error); 
      this.spinnerService.hide(); 
      this.showError(); 
     } 
    ); 
    } 

我的問題是我可以看到從getSearchProfileResponse(body)方法中的響應中傳遞的控制器的數據。但是在getProfile()方法的響應中,響應顯示爲「未定義」。任何輸入是讚賞!

回答

1

您錯過了將return.map()函數中刪除。

試試下面的代碼:

getSearchProfileResponse(body) { 
    let headers = new Headers({'Content-Type': 'application/json'}); 
    let options = new RequestOptions({headers: headers}); 
    return this.http.post(this._url, body, options) 
     .map((response:Response) => { 
     console.log(JSON.stringify(response)); 
     return JSON.stringify(response); 
     }) 
     .catch((error) => { 
     console.log("error is "+ error); 
     return Observable.throw(error); 
     }); 
    } 
+0

謝謝!這工作。 –