繁体   English   中英

使用对象作为Angular中的参数向API发送Http请求

[英]Send Http request to API with object as parameter in Angular

我有一个搜索表单,可以在我的 Web 应用程序中填写输入字段。 这些输入字段最终会出现在我的 SearchCriteria 对象中。

单击搜索按钮后,我想将该 SearchCriteria 对象发送到 API,该 API 将返回匹配 Order 对象的集合。 现在后端代码已全部就绪,我只需要执行正确的 API 调用。

这是我尝试过的,但我似乎总是收到 http 400 错误。

  getOrders(searchCriteria: SearchCriteria): Observable<Order[]> {

    let requestoptions = {
      'headers': new HttpHeaders({'Content-Type': 'application/json'}),
      'withCredentials': true
    };

    return this.http.post(environment.backend + "/api/orders/getOrders", searchCriteria, requestoptions).pipe(map((response: any) => {
      return response;
    }));
  }

请求 URL 将如下所示:

Request URL:http://localhost:8080/angular-rest/api/orders/getOrders?searchCriteria=%7B%22user%22:%7B%22firstName%22:null,%22lastName%22:null%7D,%22orderMinAmount%22:null,%22orderMaxAmount%22:null,%22orderDate%22:null,%22product%22:%22Phone%22%7D

/api/orders/getOrders 看起来像:

@RequestMapping(path = "getOrders", method = POST, consumes = "application/json", produces = "application/json")
public Collection<Order> getOrders(@RequestBody SearchCriteria searchCriteria) {
    return orderService.getOrders(searchCriteria);
}

现在我一直在阅读一些东西,但一直无法弄清楚。

我真正想要(我认为)是在我的 http 请求的请求正文中发送对象(searchCriteria),所以 URL 看起来不那么长,当然 http 请求是成功的。

我究竟做错了什么? 什么可以更好?

像这样尝试

   getOrders(searchCriteria: SearchCriteria): Observable<Order[]> {
          let headers = new HttpHeaders({'Content-Type': 'application/json'}),
          return this.http.post(environment.backend + "/api/orders/getOrders",searchCriteria, {headers})
          .pipe(map((response: any) => {
            return response;
           }));
      }

暂无
暂无

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

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