Setting the body of HttpParams() dynamically

When working with Angular 5 HttpClient, setting HttpParams() can be a bit tricky.

const body = new HttpParams()
    .set('email', 'example@example.com')
    .set('password', 'pass');

However, trying to set HttpParams() in another way doesn't seem to work as expected.

const paramsMap = new Map<any, any>();
paramsMap.set("email", "example@example.com");
paramsMap.set("password", "pass");

paramsMap.forEach((value: any, key: any) => {
    body.set(key, value);
});

Why is it not setting the values correctly? And what is the alternative approach to achieve the same result?

Answer №1

When working with HttpParams, it's important to remember that they are immutable. This means that each time you use the set() method, a new instance is returned. One way to overcome this limitation is by updating the reference as shown below:

const params = {
  test: 'true'
}

let httpParams = new HttpParams();

Object.keys(params).forEach(k => {
  httpParams = httpParams.set(k, params[k]);
});

console.log(httpParams.get('test'));

Answer №2

The APIs have slight differences, allowing you to send dynamic requests with parameters in the query string.

let paramsMap = new Map<any,any>();
paramsMap.set('username','admin');
paramsMap.set('password','admin');

let params = new HttpParams();
paramsMap.forEach((value: any, key: any) => {
  params = params.set(key, value);
});

return this.http.request<any>('post', this.url + LOGIN_URL, { 'params': params});

If you examine HttpClient methods, you can observe how it functions.

Response to the initial comment:

HttpParams is not immutable; it is used to pass parameters to the query string. To achieve this, follow these steps:

let paramsMap = new Map<any,any>();
paramsMap.set('email','example@example.com');
paramsMap.set('password','pass');   

return this.http.post<any>(this.url + LOGIN_URL, mapToObject(paramsMap));

/**
 * Recursive function that takes a Map and returns a JSON object
 * @param map
 * @returns {any}
 */
function mapToObject(map) {
  const out = Object.create(null)
  map.forEach((value, key) => {
    if (value instanceof Map) {
      out[key] = mapToObject(value)
    }
    else {
      out[key] = value
    }
  });
  return out
}

Answer №3

Give this a shot:

const searchParams = new URLSearchParams();

for (const [key, value] of Object.entries(data)) {
  console.log(`${key}: ${value}`);
  if (value !== '' && value !== undefined) {
    searchParams.append(key, value);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise when exporting a functional component within a ReactJS module

I'm encountering issues when trying to import my functional component BusinessCard, which is declared in this location https://github.com/HenryFBP/react-business-card-hfbp/blob/master/src/BusinessCard.tsx#L20 into a separate project found here https: ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

Guide on utilizing the "window" attribute within Angular framework

Recently, I came across a neat "Scroll back to top" button that caught my eye: https://www.w3schools.com/howto/howto_js_scroll_to_top.asp Despite being new to Angular, I wanted to give it a try and implement this feature myself. However, every attempt I ...

Encountered an issue while configuring the Apollo server - The type '() => void' cannot be assigned to type '() => DataSources<object>'

I need help with a TypeScript-related issue. I am struggling to implement the expected return type for the function dataSources in this scenario. Here is the code snippet: const dataSources = () => { quizzessApi: new QuizzessDataSource(); } const ...

Interfaces defined as function expressions in Typescript are not recognized when written as tuples

Trying to execute a function expression in this format: export default interface IUserManager { deleteUser: ((userId: string) => Promise<void>) | ((userName: string, userSurname: string, city: string) => Promise<void>) } from within ...

Sending common parameters to a React functional component within a TypeScript definition file

Currently, I am working on defining types in a .d.ts file for a React.FunctionComponent, specifically for a component called Tree with the following props: Tree.propTypes = { root: PropTypes.object.isRequired, children: PropTypes.func, top: PropType ...

Error encountered: Unexpected JSON token at position 0 while executing npm start on a React TypeScript project

Whenever I attempt to execute the 'npm start' command, I encounter this strange error. Everything was functioning correctly just a few hours ago, but now it refuses to launch. Even after attempting to reinstall Typescript, the issue persists. He ...

Tips on inferring a distinct generic type for every element within an array of objects

I'm working on code that creates a timeline chart for data. I want the code to accept an array of series, each containing data and various getters used to position and render the data on the chart. Below is a simplified example of the code. The actua ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Resolving Cross-Origin Resource Sharing problem in Google authentication and authorization with React, Node.js, and Passport

I am currently experiencing the same issue as described in this Stack Overflow post. Unfortunately, I have been unable to implement @Yazmin's suggested solution successfully. My goal is to develop a stack using React, Express/Node.js, and MongoDB wit ...

Clicking on the image in Angular does not result in the comments being displayed as expected

I find it incredibly frustrating that the code snippet below is not working as intended. This particular piece of code was directly copied and pasted from an online Angular course I am currently taking. The objective of this code is to display a card view ...

Fixing the Bootstrap 4 issue "Popper.js required for Bootstrap dropdowns" using Aurelia CLI and Require.js

Struggling to set up Bootstrap 4 beta in an Aurelia CLI app (v0.31.1) with requirejs and TypeScript. Despite trying different configurations, the console consistently shows this error: Uncaught Error: Bootstrap dropdown require Popper.js Here's a ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...

set a value to a concealed ngModel

Is there a way to automatically assign the same value to two input fields in Angular? In this case, the variable first needs to be set to second without requiring user input. Model export class Exp{ id: number; first: any; second: any; } H ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Obtain access to the child canvas element within the parent component

I'm currently working on an app that allows users to sign with a digital pointer. As part of the project, I have integrated react-canvas-signature. My next task is to capture the signature from the canvas and display it in a popup. According to thei ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

How to pass parameters from a directive to a child component in Angular

I am currently attempting to create a child component that can pass parameters using a directive, but I have not been able to find any tutorials on how to achieve this yet. I have tried looking at some resources, such as this one on Stack Overflow: Get re ...

Building an interactive menu in Angular: A step-by-step guide

I am working with an Interface that looks like this: export interface INavData { name?: string; url?: string | any[]; icon?: string; } To populate this Interface, I use the following data structure: export const navItems: INavData[] = [ { ...

What is the best way to combine two messages in the Global Message Service within an Angular application?

In a particular scenario, I am faced with the need to combine two error messages - one from a backend response and the other being a localized and translated text. The code snippet in question is as follows: this.globalMessageService.add( { key: ...