19

How can I do a http get request and pass an json Object

This is my json-Object

{{firstname:"Peter", lastname:"Test"}

and this Object I want to pass in the http request to get a list Of matched persons.

how is it possible? This example just shows a simple get request with a json result. How do I have to modify it?

//Component:

person:Person;
persons:Person [];
....
//Whre can I pass the person, here in the service??
getMatchedPersons(){
  this.httpService.getMatchedPersons().subscribe(
     data =>  this.persons = data,
    error => aller(error)
    );
 ); 
  

  //SERVICE
  //pass parameters?? how to send the person object here?
  getMatchedPersons(){
    return this.http.get('url').map(res => res.json());
  }

1
  • I suppose you would either have to use http.post instead, or pass the parameters in the querystring http.get('url?firstname=$1&lastname=$2')
    – Arg0n
    Jun 23, 2016 at 14:23

6 Answers 6

5

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The search field of that object can be used to set a string or a URLSearchParams object.

An example:

 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('firstname', yourFirstNameData);
 params.set('lastname', yourLastNameData);

 //Http request-
 return this.http.get('url', {
   search: params
 }).subscribe(
   (response) => //some manipulation with response 
 );
1
  • 11
    I can't believe how complicated they've made a thing that should be extremely simple :( And not just angular necessarily, but also javascript in general when needing to send variables with a get request. If we have 20 values what then? We have to loop through our object and manually do params.set(key, value)? I can't believe it... we should be able to just tell it "look, here's this object (or a stringified version). split it however you need to send it in get variables)" and that should be all. Why did they complicate things so much :(
    – MrCroft
    Oct 19, 2016 at 16:05
5

For pure javascript:

You must serialize your json to a list of parameters:

?firstname=peter&lastname=test

and append it to the URL because GET requests have no body.

There are a few ways of converting JSON to QueryParameters. They are addressed in this question: Is there any native function to convert json to url parameters?

There you can choose the poison of your liking, mine was:

function obj_to_query(obj) {
    var parts = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
        }
    }
    return "?" + parts.join('&');
}

But mind you that GET requests must obbey the URL limit that based on this answer is recomended to stay under 2000 characters to be safe:

RFC says 8000
IE8 and IE9 go as far as 2083
Search engines only read to 2048

Using Angular2 URLSearchParams

With the same method of converting a plain JSON to arguments one could use URLSearchParams as suggested by Рома Скидан:

 let params: URLSearchParams = objToSearchParams(obj);

 return this.http.get('url', {
   search: params
 }).subscribe(
   (response) => //some manipulation with response 
 );

 function objToSearchParams(obj): URLSearchParams{
    let params: URLSearchParams = new URLSearchParams();
    for (var key in obj) {
        if (obj.hasOwnProperty(key))
            params.set(key, obj[key]);
    }
    return params;
 }
2
4

Maybe you want to stringify the json object

var json = JSON.stringify(myObj);

this.http.get('url'+'?myobj='+encodeURIComponent(json))
3
  • myobj={"CompanyName":"Typhany&Co."} ... break api comunication with a string containing &? Check.
    – SparK
    Jun 23, 2016 at 14:40
  • 2
    Sure, don't forget to encode it myobj= encodeURIComponent(myobj) Jun 23, 2016 at 14:48
  • 1
    This is the shortest and best answer. Thanks you. And on the backend, with node.js simply do JSON.parse(req.query.obj). Apr 30, 2020 at 16:07
0

Use a POST request to pass objects to the server:

//SERVICE
getMatchedPersons(searchObj: any){
    return this.http.post('url', JSON.stringify(searchObj))
                    .map(res => res.json());
}

Then you can pass whatever JS object you want and send it to the server in your http request.

getMatchedPersons(searchObj: any){
    this.httpService.getMatchedPersons(searchObj: any).subscribe(
        data =>  this.persons = data,
        error => alert(error);
    );
); 
8
  • he does mention a GET request not POST Jun 23, 2016 at 14:31
  • True, but you can't pass objects with GET - can I consider this a strategic downvote? ;) Jun 23, 2016 at 14:32
  • 1
    You can, if you serialize them Jun 23, 2016 at 14:33
  • 1
    This is what @Arg0n suggested. But I would argue that it should be a GET, imagine this is a SEARCH/Filter criteria object, that in return GETs a list of search results Jun 23, 2016 at 14:35
  • 3
    @rinukkusu I agree with you that REST is not perfect, but I agree with AngJobs that object fetching and other requests that don't change stuff on server should be replayable, thus using get. If the object is simply a search filter and you use post for that, then you assume google is doing it wrong...
    – SparK
    Jun 23, 2016 at 14:43
0

Similar to AngJobs' but maybe more up-to-date?? Calling encodeURIComponent is not necessary. Here's the Angular:

const stringifiedParams = JSON.stringify(this.filterParams);
return this.http.get<any[]>(`persons`, {params: {filter: stringifiedParams}});

On the server Node deserializes the params with JSON.parse:

filter = JSON.parse(req.query.filter.toString());
0

Actually there's an easier way for flushing parameters

getMatchedPersons(myObject: any): Observable<Person[]> {
    return this.http.get<Person[]>('url', { params: { ...myObject } });
}
  • The above code represents a function that accepts a JSON object myObject as a parameter.

  • HttpClient.get method accepts an options paramter as its second paramter.

  • The options parameter contains many useful keys, but we're only interested with the params key in our case.

  • the value of params is { ...myObject }, that is- we're using the spread operator to pass all key:value pairs from an object.

Refer that this will do the job, and will not make the URL look ugly with all those ? and key=value and & characters, of course in either case those parameters won't be shown for the user since it's just an HTTP call, but still, if anyone is using a logger interceptor, they will have a clean log.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.