HttpParams is intended to be immutable. The
set
and append
methods don't modify the existing instance. Instead they return new instances, with the changes applied.let params = new HttpParams().set('aaa', 'A'); // now it has aaa
params = params.set('bbb', 'B'); // now it has both
This approach works well with method chaining:
const params = new HttpParams()
.set('one', '1')
.set('two', '2');
...though that might be awkward if you need to wrap any of them in conditions.
Your loop works because you're grabbing a reference to the returned new instance. The code you posted that doesn't work, doesn't. It just calls set() but doesn't grab the result.
let httpParams = new HttpParams().set('aaa', '111'); // now it has aaa
httpParams.set('bbb', '222'); // result has both but is discarded