简体   繁体   中英

Passing response from http.post to component.ts in angular2

I am trying to pass the response from http.post call in the typescript service component to the angular2 component so that i can display them in the frontend. Below is my service.ts and component.ts code structure.

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();
        }
      );
  }

My question is I could see the data from the controller being passed in the response in getSearchProfileResponse(body) method. But the response is showing as "undefined" in the getProfile() method's response. Any inputs is appreciated!

You have missed putting return from .map() function.

Try below code:

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);
      });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM