Advertisement
attilan

Angular append params

Nov 9th, 2021
1,063
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.     const queryParams = {
  3.       key: 'a',
  4.       key2: 150,
  5.       test: [1, 2, null, undefined, 3, 4],
  6.       testStrings: ['first', 'second'],
  7.       testNull: null,
  8.       testBool: true,
  9.     };
  10.  
  11.     let params = new HttpParams();
  12.  
  13.     const checkValueIsAppendable = (value): boolean => {
  14.       return ['number', 'string', 'boolean'].includes(typeof value);
  15.     };
  16.  
  17.     Object.entries(queryParams || {}).forEach(([key, value]) => {
  18.       if (Array.isArray(value)) {
  19.         value.filter(checkValueIsAppendable).forEach((arrayValue) => {
  20.           params = params.append(`${key}[]`, arrayValue.toString());
  21.         });
  22.       } else if (checkValueIsAppendable(value)) {
  23.         params = params.append(key, value.toString());
  24.       }
  25.     });
  26.  
  27.     console.log(params.toString());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement