Kld
Kld

Reputation: 7068

Convert object to url query parameters

What is the equivalent of $httpParamSerializer(params) from angular 1 in angular 2?

Upvotes: 3

Views: 7467

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209132

I don't know about an exact equivalent, but with URLSearchParams it will handle the encoding for you. Sucks it doesn't allow you to just pass an object, so you need to do something like

import { URLSearchParams } from '@angular/http';

let params = new URLSearchParams();
for (let key in someObj) {
  if (somObj.hasOwnProperty(key)) {
    params.set(key, someObj[key])
  }
}

If all you need is the string for some odd reason, just call params.toString(). Otherwise if you want to pass it to the Http request, just do

let options = new RequestOptions({ search: params });
http.get(url, options);

The query string will get appended to the URL in a GET request, and in a POST request, you can set it as the body

http.post(url, params);

Upvotes: 6

Related Questions