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());
  }
hamras
  • 287
  • 1
  • 5
  • 9
  • 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 '16 at 14:23

6 Answers6

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 
 );
Roman Skydan
  • 5,478
  • 4
  • 19
  • 39
  • 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 '16 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;
 }
Community
  • 1
  • 1
SparK
  • 5,181
  • 2
  • 23
  • 32
  • When you say: 'GET Requests have no body', this itself is wrong. Please refer to this https://stackoverflow.com/questions/978061/http-get-with-request-body Correct me if I misunderstood the context of your answer. – Ashish Goyal Mar 07 '19 at 08:30
  • @AshishGoyal Exactly what I meant. By convention GET requests have their body part ignored. – SparK Mar 12 '19 at 18:29
4

Maybe you want to stringify the json object

var json = JSON.stringify(myObj);

this.http.get('url'+'?myobj='+encodeURIComponent(json))
null canvas
  • 10,201
  • 2
  • 15
  • 18
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);
    );
); 
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
  • he does mention a GET request not POST – null canvas Jun 23 '16 at 14:31
  • True, but you can't pass objects with GET - can I consider this a strategic downvote? ;) – Maximilian Riegler Jun 23 '16 at 14:32
  • 1
    You can, if you serialize them – null canvas Jun 23 '16 at 14:33
  • Might as well switch to POST at this point, if you have to deserialize them on serverside. – Maximilian Riegler Jun 23 '16 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 – null canvas Jun 23 '16 at 14:35
  • Are you suggesting because the method is called "GET" it should be used for getting things? Clearly you have never used any big APIs before like Twitter and the like, where you always POST. – Maximilian Riegler Jun 23 '16 at 14:38
  • 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 '16 at 14:43
  • Definitely should stick to what the HTTP specs say... GET vs POST is something we shouldn't take lightly. One source for reasoning: https://medium.com/@suhas_chatekar/why-you-should-use-the-recommended-http-methods-in-your-rest-apis-981359828bf7 – Kris Boyd Mar 03 '19 at 22:05
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());
jbobbins
  • 1,221
  • 3
  • 15
  • 28
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.

Mohamed Karkotly
  • 1,364
  • 3
  • 13
  • 26