I have been looking for a way to pass query paramters 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?
A more concise solution:
You can pass it like this
let param: any = {'userId': 2}; this.http.get(
${ApiUrl}, {params: param})
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
you could also do
If you need inherited properties then remove the hasOwnProperty accordingly.
search property of type URLSearchParams in RequestOptions class is deprecated in angular 4. Instead, you should use params property of type URLSearchParams.
You can (in version 5+) use the fromObject and fromString constructor parameters when creating HttpParamaters to make things a bit easier
or:
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 asHttpParams()
and the property within theget()
function is now calledparams
instead ofsearch
.I actually prefer this syntax as its a little more parameter agnostic. I also refactored the code to make it slightly more abbreviated.
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.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.