简体   繁体   中英

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?

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

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