The new HTTP client works with immutable request object and all its consistuent parts like HttpParams
and HttpHeaders
. To understand why see Why is http request and all its constituent parts like HttpHeaders and HttpParams are immutable or read the article Insider’s guide into interceptors and HttpClient mechanics in Angular.
That is why append
method merges the parameters and returns the new instance of the merged HttpParams
object on each call to append
:
/**
* Construct a new body with an appended value for the given parameter name.
*/
append(param: string, value: string): HttpParams {
return this.clone({param, value, op: 'a'});
}
private clone(update: Update): HttpParams {
const clone = new HttpParams({encoder: this.encoder}); <-------
clone.cloneFrom = this.cloneFrom || this;
clone.updates = (this.updates || []).concat([update]);
return clone; <--------
}
So here:
var params = new HttpParams().append('a', '1').append('b', '2');
the append
with b
parameter updates the object returned by the append
with a
parameter.
While with this approach
var params = new HttpParams();
params.append('a', '1');
params.append('b', '2');
the append
always updates initial state of the HttpParams
and all intermediary append
operations effectively ignored.
So you have to use the previous returned value:
var params = new HttpParams();
params = params.append('a', '1');
params = params.append('b', '2');
Or use the shortcut with fromObject
:
let searchParams = new HttpParams({
fromObject: {
query: query,
sort: sort,
order: order
}
});
const modified = req.clone({params: searchParams});
Or use setParams
method on a request directly:
const modified = req.clone({setParams: {'query': query, 'sort': sort, 'order': order}});
Also, since 5.1.x you can pass object directly instead of an instance of HttpParams:
const params = {
'a': '1',
'b': '2'
};
this.http.get('...', { params })