HttpClient POST 与 HttpParams

HttpClient POST with HttpParams

我正在尝试 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));

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

如果我使用 .get() 但不使用 .post() 针对 POST端点。

我错过了什么?

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

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

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

我认为这是因为您将参数作为 object 传递。

参考下面的例子

const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')

让body = new HttpParams();

body = body.set('username', 用户名);

body = body.set('password', 密码);

http .post('/api', body, { headers: 我的标题), })