Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the set and append methods of angulars HttpParams object?

The method description for append is

Construct a new body with an appended value for the given parametername.

while the method description for set is

Construct a new body with a new value for the given parametername.

But with append you can set a new value for a parametername as well. Both methods create the parameter when it doesn't exist so i was wondering why there are 2 methods that pretty much do the same thing and when you should use one instead of the other.

thank you

like image 387
Maurice Avatar asked Aug 23 '18 07:08

Maurice


People also ask

How to set HttpParams angular?

To use HttpParams , you need to import it first as shown below. import { HttpClient,HttpParams } from '@angular/common/http'; Then create an instance of the HttpParams class.

What is http params?

@Deprecated public interface HttpParams. HttpParams interface represents a collection of immutable values that define a runtime behavior of a component. HTTP parameters should be simple objects: integers, doubles, strings, collections and objects that remain immutable at runtime.


2 Answers

Set sets a unique value for the given key :

params.set('toto', '1').set('toto', '2') // toto=2

Append appends another value for the given key :

params.set('toto', '1').append('toto', '2') // toto=1&toto=2
like image 193
Jscti Avatar answered Oct 11 '22 05:10

Jscti


HttpParams values are array of values.

When you set the value, it will override all the values in the array.

When you append the value, it will push new values on the existing array.

You can check the difference like this:

    let paramsSet = new HttpParams();
    paramsSet = paramsSet.set('paramName', 'set');

    let paramsAppend = new HttpParams();
    paramsAppend = paramsAppend.set('paramName', 'append');

    paramsSet = paramsSet.set('paramName', 'set2');
    paramsAppend = paramsAppend.append('paramName', 'append2');

    console.log(paramsSet.getAll('paramName'));
    console.log(paramsAppend.getAll('paramName')); 

paramsSet will only have ['set2'] as the value, while paramsAppend will have ["append", "append2"].

like image 26
Roberto Zvjerković Avatar answered Oct 11 '22 05:10

Roberto Zvjerković