Search code examples
angulartypescriptangular-httpclient

HttpClient POST with HttpParams


I am attempting to POST to an endpoint that requires arguments are passed as query string parameters and not via the POST body.

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

This is returning a 404 as the call does not include any querystring parameters. I have verified this by looking at the network call.

This same code does work for me against GET requests if I am using .get() but isn't working with .post() against a POST endpoint.

What am I missing?


Solution

  • The 2nd parameter of post is the http body that you want to send in the request. If there is no body then pass null for the argument. Then pass the params as the 3rd argument of the call.

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

    The reason that get has a different method signature is that you can't pass a http body with a http get call.