Using set()
From Angular Official Documentation of set()
set(param: string, value: string | number | boolean): HttpParams
Returns HttpParams: A new body with the new value.
Now, lets see how we can add some parameters -
const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");
Notice that we are constructing the HTTPParams object by chaining set() methods. The reason is HTTPParams is immutable.
Every time a call to set method will return a new HttpParams object with the new value. We need to first grab the returned HttpParams object and then use that for further modification.
So, If we do the following, it will not work
const params = new HttpParams(); // empty HttpParams object
params.set('aaa', '111'); // lost
params.set('bbb', "222"); // lost
We are only calling set
but not keeping the returned HttpParams
object. So, lastly we would have an empty HttpParams object, and the two calls to set would have add no effect. To make it work, wee need to do the following -
const params = new HttpParams(); // empty HttpParams object
params = params.set('aaa', '111'); // storing the returned HttpParams object, now **it has aaa**
params = params.set('bbb', "222"); // add another parameter and store it. so now **it has both aaa and bbb**
Using fromString
you can also use fromString to create httpParams. It's good when you already have a Query parameters string prepared. you can do it using the following syntax
const params = new HttpParams({
fromString: 'aaa=111&bbb=222'
});
httpParams.set('bbb', '222');
should work. I tried that first and was very confused. But replace that line withhttpParams = httpParams.set('bbb','222');
works. for those who are only setting 2, the chaining answer from another User below is also nice. – Rosenblatt