Eugene Goldberg
Eugene Goldberg

Reputation: 15544

Angular - how to properly return JSON response from HTTP POST

In my Angular 7 application I have a requirement to submit a search query via HTTP POST:

Component:

onSubmit() {
    this.dataService.doSearch(this.model)
    .subscribe(
      data => {
        const ds = data.content as string [];
     this.myDs = data.content as string [];  // FILL THE ARRAY WITH DATA.
      console.log(ds);
   },
   (err: HttpErrorResponse) => {
     console.log (err.message);
   }
 );
  }

Data Service:

doSearch (issue: Issue): any {
  this.dialogData = issue;
  const requestId = this.dialogData['requestId'];
  const application = this.dialogData['application'];
  const component = this.dialogData['component'];
  const feature = this.dialogData['feature'];
  const isOn = this.dialogData['isOn'];
  const dataObject = {requestId: requestId, application: application, component: component,
    feature: feature,  isOn: isOn};
  this._http.post('/api/search', dataObject).subscribe({
  next: data => this.searchResponceData = data.json,
    error: error => console.error('There was an error!', error),
})
.map((res: Response) => res.json());
}

the '/api/search' endpoint is handled in node / express part, which is also used to serve the Angular part.

node / express does its part and returns the proper JSON back to the Data Service, but I can't quite figure out how to pass that returned data back to the Component, since the 'subscription' does not have the 'map' method.

What is the proper way of returning the data from underlying POST in this particular scenario?

Upvotes: 0

Views: 94

Answers (1)

German Cosano
German Cosano

Reputation: 107

With .pipe() you will be able to use .map after all.

In my opinion best way is return as promise the http request and then in your component subscribe.

Of course you will be able to iterate over the Data as always

.subscribe( res => someVar = res.map( ...someCode))

Upvotes: 1

Related Questions