Search code examples
angularhttppostangular2-observables

QueryParameter on POST


I'm using Angular2/4 to build an web app.

I need to send the object to the rest api using query parameters. My endpoint will only accept an object through the url like this:

localhost:8080/api/node?type=bills&quantity=2

my service currently its like this:

addInstance(instance: Instance) {
  const params = {
    type: instance.type,
    quantity: instance.quantity
  };
  return this.http.post(this.baseUrl, params, {headers: this.headers}) 
  .map(res => {
    return res.json();
  });
}

But it's not working and in the console log says there's no object passing in the url. How can i provide a correct call to the API?


Solution

  • You are currently sending body parameters, not url parameters, and your endpoint is expecting url parameters. You can, however, construct url params in angular using URLSearchParams

    Try:

    addInstance(instance: Instance) {
       const params = new URLSearchParams();
       params.set('type', instance.type);
       params.set('quantity', instance.quantity);
    
       return this.http.post(this.baseUrl, body?, {params: params}  )
          .map(res => {
             return res.json();
          });
    }
    

    You can also just construct the url directly using string concatenation.

    Although, since this is a post request you should figure out with your api endpoint what the body of the request should be since typically a post request contains one. Otherwise you should change the api endpoint to make this a get request instead. Or make the api endpoint expect body parameters instead of url parameters.