Home > Software design >  adding multiple query params in angular 14
adding multiple query params in angular 14

Time:12-22

I am building a multi item filter for my app and I need to send multiple queryparameters in API to get filtered items.

My question is that is there any other way than adding all the queryParams by hand since there are like 40-50 options to filter with. Can that somehow be done programmatically?

Pretty sure it would work if i manually made an object but im interested if there's a way to do it easier.

link to filter

CodePudding user response:

You could create an object to keep track of all the filter option.

Then simply use JSON.stringify to convert it to JSON.

You could also ignore the null and undefined value by passing in a replacer function.

let opt = {
    a: 'string',
    b: 5.1,
    c: true,
    d: { e: 'object' },
    f: ['array'],
    g: null,
    h: undefined,
  };
  
console.log(JSON.stringify(opt, (key, value) => {
    if (value !== null) return value;
}));

CodePudding user response:

Yes, it is possible to programmatically generate query parameters.

You could maintain an array of param key/values using Object.entries to convert an object to an array of key/value pairs, and Object.fromEntries to convert from an array of key/value pairs back to an object.

const params = { currency: 'USD', language: 'en-US' }
// convert to [['currency', 'USD], ['language', 'en-US']]
const arrayOfParams = Object.entries(params) 
// convert back to { currency: 'USD', language: 'en-US' }
const paramsObj = Object.fromEntries(arrayOfParams) 

Then use HttpParams to serialize/deserialize an object to query params:

import { HttpParams } from '@angular/common/http'
const paramsObj = { currency: 'USD', language: 'en-US'}
const params = new HttpParams({ fromObject: paramsObj })

/* Serializes the body to an encoded string, 
*  where key-value pairs (separated by =) are separated by &s. 
*/
const queryStr = params.toString() 
  • Related