Reputation: 1187
I have got a params
variable in Angular service which is of type HttpParams
.
When I do
params.set('sortby', sortby.toString());
or
params.set('top', top.toString());
both of this are working and getting added to params
variable and passing on to the API.
However the issue is when I have a route param defined as 'query'
in the API. I failed to understand why my code,
params.set('query', query.toString());
not working at all. It just don't get added to the params list. I assume it is something to do with the name 'query'
. Updating API is not a choice at this moment.
Is there a way I could make 'query'
work?
API Call :
Try updating directly to the request from chrome console. Even then I could not find the query param.
EDIT : newParams()
That is returning the HttpParams with a correct codec
protected newParams(): HttpParams {
return new HttpParams({
encoder: PARAMETER_CODEC
});
}
And Encoder is ,
class ParameterCodec implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(value: string): string {
return encodeURIComponent(value);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(value: string): string {
return decodeURIComponent(value);
}
}
const PARAMETER_CODEC = new ParameterCodec();
Upvotes: 2
Views: 348
Reputation: 2039
If you are wondering why no parameters get passed, there is a key hint in the referenced HttpParams docs
This class is immutable - all mutation operations return a new instance.
Basically you should be able to send params/query by chaining like this to have multiple params:
const params = new HttpParams()
.set('query', 'value here')
.set('another_param', 'value_here')
.set('sortby', sortby.toString());
return this.httpClient.get('my url', { params })
If you want to append HttpParams
conditionally, use a variation of this instead, Ex:
let params = new HttpParams();
if ( limit ) {
params = params.set('limit', String(limit));
}
params = params.set('search', keyword);
Upvotes: 2