168

I have been looking for a way to pass query parameters into an API call with the new HttpClientModule's HttpClient and have yet to find a solution. With the old Http module you would write something like this.

getNamespaceLogs(logNamespace) {

    // Setup log namespace query parameter
    let params = new URLSearchParams();
    params.set('logNamespace', logNamespace);

    this._Http.get(`${API_URL}/api/v1/data/logs`, { search: params })
}

This would result in an API call to the following URL:

localhost:3001/api/v1/data/logs?logNamespace=somelogsnamespace

However, the new HttpClient get() method doesn't have a search property, so I am wondering where to pass in the query parameters?

Jakub Šturc
  • 32,938
  • 24
  • 85
  • 107
joshrathke
  • 6,536
  • 5
  • 19
  • 36
  • 2
    With Angular 7, you can write your params as an object and use it like this: `this.httpClient.get(url, { params }` Check out https://stackoverflow.com/a/54211610/5042169 – Jun711 Jan 16 '19 at 06:54

8 Answers8

253

I ended up finding it through the IntelliSense on the get() function. So, I'll post it here for anyone who is looking for similar information.

Anyways, the syntax is nearly identical, but slightly different. Instead of using URLSearchParams() the parameters need to be initialized as HttpParams() and the property within the get() function is now called params instead of search.

import { HttpClient, HttpParams } from '@angular/common/http';
getLogs(logNamespace): Observable<any> {

    // Setup log namespace query parameter
    let params = new HttpParams().set('logNamespace', logNamespace);

    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
}

I actually prefer this syntax as its a little more parameter agnostic. I also refactored the code to make it slightly more abbreviated.

getLogs(logNamespace): Observable<any> {

    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, {
        params: new HttpParams().set('logNamespace', logNamespace)
    })
}

Multiple Parameters

The best way I have found thus far is to define a Params object with all of the parameters I want to define defined within. As @estus pointed out in the comment below, there are a lot of great answers in This Question as to how to assign multiple parameters.

getLogs(parameters) {

    // Initialize Params Object
    let params = new HttpParams();

    // Begin assigning parameters
    params = params.append('firstParameter', parameters.valueOne);
    params = params.append('secondParameter', parameters.valueTwo);

    // Make the API call using the new parameters.
    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })

Multiple Parameters with Conditional Logic

Another thing I often do with multiple parameters is allow the use of multiple parameters without requiring their presence in every call. Using Lodash, it's pretty simple to conditionally add/remove parameters from calls to the API. The exact functions used in Lodash or Underscores, or vanilla JS may vary depending on your application, but I have found that checking for property definition works pretty well. The function below will only pass parameters that have corresponding properties within the parameters variable passed into the function.

getLogs(parameters) {

    // Initialize Params Object
    let params = new HttpParams();

    // Begin assigning parameters
    if (!_.isUndefined(parameters)) {
        params = _.isUndefined(parameters.valueOne) ? params : params.append('firstParameter', parameters.valueOne);
        params = _.isUndefined(parameters.valueTwo) ? params : params.append('secondParameter', parameters.valueTwo);
    }

    // Make the API call using the new parameters.
    return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
Alexander Abakumov
  • 10,817
  • 10
  • 71
  • 111
joshrathke
  • 6,536
  • 5
  • 19
  • 36
  • 7
    The first snippet is wrong. `let params = new HttpParams(); params.set(...)` won't work as expected. See https://stackoverflow.com/questions/45459532/why-httpparams-doesnt-work-in-multiple-line-in-angular-4-3/45459672#45459672 – Estus Flask Aug 02 '17 at 21:11
  • @joshrathke Could you please add how to add header and params together? – Savad KP Dec 19 '17 at 03:55
  • 3
    @SavadKP you can set them like this this.http.get(url, {headers: headers, params: params}); and read about new HttpHeaders like HttpParams – Junaid Feb 15 '18 at 07:55
  • I guess `new HttpParams({fromObject: { param1: 'value1', ... }});` is the easiest approach (angular 5+) then `params.set(...)`. – Pankaj Prakash Feb 07 '19 at 06:16
91

You can (in version 5+) use the fromObject and fromString constructor parameters when creating HttpParamaters to make things a bit easier

    const params = new HttpParams({
      fromObject: {
        param1: 'value1',
        param2: 'value2',
      }
    });

    // http://localhost:3000/test?param1=value1&param2=value2

or:

    const params = new HttpParams({
      fromString: `param1=${var1}&param2=${var2}`
    });

    //http://localhost:3000/test?paramvalue1=1&param2=value2
JayChase
  • 9,520
  • 2
  • 40
  • 46
  • 30
    This is not needed anymore. You can just pass directly a JSON object to HttpClient. `const params = {'key': 'value'}` to: `http.get('/get/url', { params: params })` – danger89 Mar 04 '18 at 11:50
  • 7
    @danger89 True. But be warned: only string or string[] values allowed! – Jose Enrique May 14 '18 at 14:59
  • Saved huge amount of my time. I was constructing url by appending query params as string to the request url. – Pankaj Prakash Feb 07 '19 at 06:17
22

You can pass it like this

let param: any = {'userId': 2};
this.http.get(`${ApiUrl}`, {params: param})
Paul Rooney
  • 17,518
  • 8
  • 35
  • 57
Pradeep B P
  • 296
  • 3
  • 8
13

A more concise solution:

this._Http.get(`${API_URL}/api/v1/data/logs`, { 
    params: {
      logNamespace: logNamespace
    } 
 })
Darwayne
  • 1,330
  • 14
  • 14
7

With Angular 7, I got it working by using the following without using HttpParams.

import { HttpClient } from '@angular/common/http';

export class ApiClass {

  constructor(private httpClient: HttpClient) {
    // use it like this in other services / components etc.
    this.getDataFromServer().
      then(res => {
        console.log('res: ', res);
      });
  }

  getDataFromServer() {
    const params = {
      param1: value1,
      param2: value2
    }
    const url = 'https://api.example.com/list'

    // { params: params } is the same as { params } 
    // look for es6 object literal to read more
    return this.httpClient.get(url, { params }).toPromise();
  }
}
Jun711
  • 2,485
  • 3
  • 20
  • 43
4

joshrathke is right.

In angular.io docs is written that URLSearchParams from @angular/http is deprecated. Instead you should use HttpParams from @angular/common/http. The code is quite similiar and identical to what joshrathke have written. For multiple parameters that are saved for instance in a object like

{
  firstParam: value1,
  secondParam, value2
}

you could also do

for(let property in objectStoresParams) {
  if(objectStoresParams.hasOwnProperty(property) {
    params = params.append(property, objectStoresParams[property]);
  }
}

If you need inherited properties then remove the hasOwnProperty accordingly.

Sven
  • 73
  • 7
4

If you have an object that can be converted to {key: 'stringValue'} pairs, you can use this shortcut to convert it:

this._Http.get(myUrlString, {params: {...myParamsObject}});

I just love the spread syntax!

Jeremy Moritz
  • 10,834
  • 6
  • 30
  • 37
2

search property of type URLSearchParams in RequestOptions class is deprecated in angular 4. Instead, you should use params property of type URLSearchParams.

sanket patel
  • 459
  • 4
  • 7