Reputation: 2163
I am trying to make an HTTP get request with an object as param. It's this possible? I already tried it multiple ways but without success. It works if I send only strings, not the entire class
export class City {
id: number;
name: string;
}
const params = new HttpParams().set('city', city)
return this.http.get('http://localhost:3000/api/place/', {params})
Upvotes: 1
Views: 2097
Reputation: 4897
Here's a little helper function that JSON-encodes any Object-like properties in an object, leaves primitives as string. Obviously you need to decode the query in the backend. Change _.isObjectLike to some other way of checking the type if you don't want lodash.
require * as '_' from 'lodash';
private objectToHttpParams(obj: any) {
return Object.entries(obj || {})
.reduce((params, [key, value]) => {
return params.set(key, _.isObjectLike(value) ? JSON.stringify(value) : String(value));
}, new HttpParams());
}
// use:
const params = this.objectToHttpParams({city});
Upvotes: 1