将响应从http.post传递给angular2中的component.ts

时间:2017-06-06 03:31:28

标签: angular typescript

我正在尝试将typescript服务组件中的http.post调用的响应传递给angular2组件,以便我可以在前端显示它们。下面是我的service.ts和component.ts代码结构。

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 个答案:

答案 0 :(得分: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);
      });
  }