URL Parameters, Query Parameters, httpparams in Angular HttpClient

This post is a guide on how to Pass the URL Parameters or Query Parameters along with the HTTP Request using the HttpClient in Angular. We will be using HttpParams to add the URL Parameter, which is then used by the GET, POST, PUT & PATCH etc methods to send an HTTP request to the back end API. The URL Parameters also are known by the name Query strings, Query Params, Get Params, etc.

Refer to our tutorial on Angular HTTP get example & Angular HTTP Post Example

The HttpParms were known as URLSearchParams until Angular 4

Applies to: Angular 5 to the latest edition i.e. Angular 8, Angular 9. Angular 10, Angular 11

The URL Parameters

In the Angular HttpClient GET Example article, we created a GitHubService. The Service issued GET Request to GitHub API Endpoint to retrieve the List of Repositories belonging to a particular User. 

The GitHub API also has a set of parameters, which allows us to specify how we want to sort, which page to retrieve, No of Entries per page and type of the Repository to retrieve, etc.

For Example

The Above query will return the result sorted on the description and retrieves only the second page. The string sort=description&page=2 after the question mark is called URL Parameter or Query strings /Query Parameters. The Question mark is used as a separator. The URL Parameters are also known as the GET params.

HttpParams()

We add the URL parameters using the helper class HttpParams.  The HttpParams is passed as one of the arguments to HttpClient.get method.

To use HttpParams, you need to import it first as shown below.

Then create an instance of the HttpParams class.

And then call the httpClient.get method passing the params as the argument.

The following are the list of method available in HttpParams class

HttpParams.set 

Construct a new body with a new value for the given parameter name. If the parameter already exists then it is replaced else it is added.

HTTPParams is immutable

The HttpParams object is immutable. Every time you call a set method on Params object, it will create and return a new instance of the Params.

For Example

The following code does not work

Each call to set method does not add the options to the existing HttpParams instance, but creates a new instance from the existing instance and returns it.

To work around, you can use the code as follows

Or you can try this

HttpParams.append

Construct a new body with an appended value for the given parameter name. Always appends the value irrespective of whether the parameter exists. The page parameter is appended twice in the following example.

The URL Is constructed as page=2&page=3&sort=name

You can also use the append method similar to the Set method

HttpParams.has

Returns true if the given parameter name already exists in the HttpParams

HttpParams.get

Get the first value for the given parameter name, or null if it’s not present.

HttpParams.getAll

Get all values as for the given parameter name, or null if it’s not present.

HttpParams.keys

Get all the parameter names for this body.

HttpParams.delete

Deletes the parameter and returns the new parameter collection.  You can delete using the parameter name or by using the name & value. If no argument is specified, then all parameters are deleted.

HttpParams.toString

Serialize the body to an encoded string, where key-value pairs (separated by =) are separated by &s.

Http Parameters from a string

Another way to pass the value is to use the fromString shortcut

Http Parameters from an object

Without params

You can also add the parameters directly to the URL, without going through the HttpParams as shown below.

Angular Httpparams Example

We are updating the project, which was created in the tutorial Angular Http GET Example.

app.module

Import the httpClientModule from the @angular/common/http package.

Declare it in Imports metadata array in app.module.ts

Passing the URL Parameters

Open the github.service.ts.

Import the HttpClient & HttpParams from the @angular/common/http. We also require the Observable module from RxJs

Inject HttpClient in the Constructor

In the GetRepos method create the params object

And use the params when calling the httpClient.get method as shown below

The complete github.service.ts

App.component.ts

App.component.html

Summary

We learned how to pass Get Parameters or request parameters when we invoke the HTTP get Request using httpClient.get method

References

12 thoughts on “URL Parameters, Query Parameters, httpparams in Angular HttpClient”

  1. You used parameter are string, that works. But have tried
    Number type ? id, or id.toString(), neither worked.

    getQuote(id: number): Observable {
    let httpParams = new HttpParams();
    httpParams = httpParams.set(‘request_no’, id);
    return this.http.get(this.baseUrl+’/getquote’,
    {params: httpParams})
    }

    If parameter is Number, Tomcat server side (Springboot application server) : HttpServletRequest request
    request.getParameter(“request_no”) will return [Object Object]. What is this type and how can parse it into passed number ?

    Thanks

    1. This should work
      httpParams = httpParams.set(‘request_no’, id.toString());

      Open the network tab in chrome and check the URL generated. You should see it as follows

      baseURL/getquote?request_no=id

  2. Hi, have a questio, Im using (Angular7)
    searchProducto(term: string): Observable {
    if (!term.trim()) {return of([]);}
    let headers = new HttpHeaders().set(‘Content-Type’, ‘application/json’);
    let params = new HttpParams().set(‘Gpclave’, term );
    return this.http.get(${ubi}/,{params, headers})
    .pipe( retry(2),
    tap(listaDemosp => console.log(listaDemosp) ) )
    }
    If term=Peter get all the info, now if term=Pe, get nothing
    Any help ??

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top