带有 HttpParams 的 HttpClient POST

Pat*_*ick 2 typescript angular angular-httpclient

我正在尝试 POST 到一个端点,该端点需要将参数作为查询字符串参数传递,而不是通过 POST 正文传递。

const params = new HttpParams()
  .set('param1', '1')
  .set('param2', '2');

const url = environment.apiUrl + 'Service/Endpoint';

return this
  .httpClient
  .post<ServiceResponse>(url, { params })
  .pipe(map(res => res.httpStatusCodeSuccess));
Run Code Online (Sandbox Code Playgroud)

这将返回 404,因为调用不包含任何查询字符串参数。我通过查看网络调用验证了这一点。

如果我正在使用但不针对 POST 端点,那么相同的代码确实可以针对 GET 请求对我起作用。.get().post()

我缺少什么?

Igo*_*gor 5

第二个参数post是您要在请求中发送的 http 正文。如果没有主体,则通过null参数。然后将参数作为调用的第三个参数传递。

  .post<ServiceResponse>(url, null, { params: params })

Run Code Online (Sandbox Code Playgroud)

具有不同方法签名的原因get是您无法通过 http get 调用传递 http 正文。