简体   繁体   中英

Angular 2 - Http Get request - pass json Object

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

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

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

Maybe you want to stringify the json object

var json = JSON.stringify(myObj);

this.http.get('url'+'?myobj='+encodeURIComponent(json))

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM