What are the functions of HTTP query params, how to send an array in the Get Request in Angular?
There are many functions for the query string. Query string starts from question mark (?). For using different properties, we need to use the ampersand operator (&).
let’s assume the following URL
https://medium.com?user=vikas-kohli&id=3&is-active=1
In the above URL, we‘re using three query params
a. user
b. id
c. is-active
So how do we add these properties in Angular, there are two ways.
//IMport
import { HttpClient, HttpParams } from '@angular/common/http';
//import url files
import {URLS} from './urls';//initalize in the constructor function
constructor(
private http: HttpClient){
}
1st consider, we’ll use direct 3 variables or 1variable w/o httpParams of HTTP library. Without any HTTP param method as we’re not using any library thing here.
getData(params){
return this.http.get(`${URLS.GET_DATA}?user=params.user&id=params.id&is-active=params.isActive`)
}or directly use 3 varaibles
getData(user,id,isActive){
return this.http.get(`${URLS.GET_DATA}?user=user&id=id&is-active=isActive`)
}
2nd, we’ll do using HTTP params of HTTP library.
For using this we need to use set
method
//assume get data function
getData(params){
//1st option we're using http params method and then iterating the params object using forin loop and adding that queryParams object to params property in http and URL.get_DATA is defined in the urls file
let queryParams = new HttpParams();
for (let key in params) {
queryParams = queryParams.set(key, params[key]);
}
return this.http.get(`${URLS.GET_DATA}`, {
params: queryParams
})
}
Here we initalize queryParams of HTTPParams type and then we can use all the properties , in the above we're using set method
HTTP Params method
- set
- append
- get
- getAll
- has
- keys
- delete
- toString
Let’s discuss one by one.
- Let’s begin with the
set
method, this method I use in the above function, there I m using for in loop so all the objects in the params can directly iterate and set. Syntax set(param: string, value: string)
let queryParams = new HttpParams();
// queryParams.set(keyname, keyvalue)
queryParams.set(user,'vikas');
queryParams.set(id,'1') //make sure you're sedning string values if not string then use toSTring function
queryParams.set(is-active,'1')
2. append
Using this we can send an array also in the query string. Syntax append(param: string, value: string)
let’s assume we need to send arr = [‘abc’, ’def’, ’ghi’, ’jkl’] in the test property.
let queryParams = new HttpParams();let arr = [‘abc’,’def’,’ghi’,'jkl'];
queryParams.append('test',arr[0]);
queryParams.append('test',arr[1]);
queryParams.append('test',arr[2]);
queryParams.append('test',arr[3]);
If we want to directly iterate as the above one is a long method and static option, we must choose dynamic.
for (let k = 0; k < arr.length; k++) {
queryParams.append('test', arr[k]);
)Let's assume the url is https://abc.com then after adding the query params using append method and after add url string and queryparams in the http object, the url will look likehttps://abc.com?test=abc&test=def&test=ghi&test=jkl
3.get
method:- Using this method we can get the value of the property name. Its syntax set(param: string): string | null
Here return type is string or null, as whenever we set the value as a string so the string is one of the data types and it may not necessary that property exists which we’re going to fetch so for that it gives null value.
let queryParams = new HTTPParams()
queryParams.set('test','abc')console.log(queryParams.get('test')); // It will return the value of the test i.e abclet queryParams = new HTTPParams()
queryParams.set('test','abc')
queryParams.set('test','def')
queryParams.set('test','ghi')
queryParams.set('test','jkl');https://abc.com?test=abc&test=def&test=ghi&test=jkl
console.log(queryParams.get('test')); // It will also return the value of the test i.e abc becuase it returns the first instance
4.getAll
method:- Using this method we can get the values of the property name. Its syntax set(param: string): string[] | null
Here the string type is the same but instead of a string, it will give a string array as one property that can be used multiple times in the URL.
let queryParams = new HTTPParams()
queryParams.set('test','abc')
queryParams.set('test','def')
queryParams.set('test','ghi')
queryParams.set('test','jkl');console.log(queryParams.get('test')); // It will also return all the values of the test
[‘abc’,’def’,’ghi’,'jkl'] //printed valueconsole.log(queryParams.get('other')) // as there is no such property it will return null
null //printed value
5. has
method:- Using this method we can check whether that property exists or not.Its syntax has(param: string): boolean
let queryParams = new HTTPParams()
queryParams.set('test','abc')
queryParams.set('test','def')
queryParams.set('test','ghi')
queryParams.set('test','jkl');console.log(queryParams.has('other')) //Returns falseconsole.log(queryParams.has('test')) //Returns true
6. keys
method:- Using this method we can get all the properties of the query string that exist in the URL. Its syntax keys(): string[]
https://abc.com?test=abc&test=def&test=ghi&test=jkl&name=hello&page=3&index=2let queryParams = new HTTPParams()
queryParams.set('test','abc')
queryParams.set('test','def')
queryParams.set('test','ghi')
queryParams.set('test','jkl')
queryParams.set('name','hello')
queryParams.set('page','3')
queryParams.set('index','2');console.log(queryParams.keys()) //returns ['test','name','page','index']let queryParams = new HTTPParams()console.log(queryParams.keys()) //returns [] array as in the above there is no query paramater set or append
7. delete
method:- Using this method we can delete the properties of the query parameters and in return, it provided new HTTP Params. Its syntax is delete(param: string, value?: string): HttpParams
let queryParams = new HTTPParams()
queryParams.set('test','abc')
queryParams.set('test','def')
queryParams.set('test','ghi')
queryParams.set('test','jkl')
queryParams.set('name','hello')
queryParams.set('page','3')
queryParams.set('index','2');We can see value is an optional paramaterCase 1
queryParams= queryParams.delete('test', 'jkl'); //Deletes the parameter test whose value is 'jkl' and then after it returns the new http params which we assign back to the query paramsCase 2
queryParams= queryParams.delete('test'); //Now we haven't povide any value with the parameter so it will delete all the occurences of test in the query params objectCase 3
queryParams= queryParams.delete(''); //if empty parameter will pass then it will delete all the query params that means queryParams initialize to empty object.
8. toString
method:- Using this method we get all the query parameters that are set as a single value in a string data type. Its syntax is toString(): string
let queryParams = new HTTPParams()
queryParams.set('test','abc')
queryParams.set('test','def')
queryParams.set('test','ghi')
queryParams.set('test','jkl')
queryParams.set('name','hello')
queryParams.set('page','3')
queryParams.set('index','2');console.log(queryParams.toString()); //Returns test=abc&test=def&test=ghi&test=jkl&name=hello&page=3&index=2Suppose we have assign any query paramslet queryParams = new HTTPParams()
console.log(queryParams.toString()) //Return empty string
Hope it helps to go through all the HTTPParams method.
Happy Coding with HTTP Module 😊