Reputation: 287
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());
}
Upvotes: 19
Views: 36003
Reputation: 1517
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.
Upvotes: 0
Reputation: 1291
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());
Upvotes: 0
Reputation: 5211
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
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;
}
Upvotes: 5
Reputation: 10613
Maybe you want to stringify the json object
var json = JSON.stringify(myObj);
this.http.get('url'+'?myobj='+encodeURIComponent(json))
Upvotes: 4
Reputation: 5748
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
);
Upvotes: 5
Reputation: 23506
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);
);
);
Upvotes: 0