简体   繁体   English

Angular - 如何从 HTTP POST 正确返回 JSON 响应

[英]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:在我的 Angular 7 应用程序中,我需要通过 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. '/api/search' 端点在 node / express 部分处理,它也用于为 Angular 部分提供服务。

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. node / express 完成它的一部分并将正确的 JSON 返回给数据服务,但我无法弄清楚如何将返回的数据传递回组件,因为“订阅”没有“映射”方法。

What is the proper way of returning the data from underlying POST in this particular scenario?在这种特定情况下,从底层 POST 返回数据的正确方法是什么?

With .pipe() you will be able to use .map after all.使用 .pipe() 你将能够使用 .map 毕竟。

In my opinion best way is return as promise the http request and then in your component subscribe.在我看来,最好的方法是作为承诺返回 http 请求,然后在您的组件中订阅。

Of course you will be able to iterate over the Data as always当然,您将能够像往常一样迭代数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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