The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts

getHttpParams = () => {
    const httpParamsInstance = new HttpParams();
    console.log(this.userForm.controls)
    Object.keys(this.userForm.controls).forEach(key => {
        console.log(this.userForm.get(key).value)
        const value = this.userForm.get(key).value;
        if (value){
            console.log('Adding key and value' + httpParamsInstance.append(key, value)) ==> Correct value displayed
            httpParamsInstance.append(key, value);      ==> However, when checking the HttpParams map, it returns null
            console.log(httpParamsInstance)
        }
    });
    return httpParamsInstance;
}

onSubmit() {
    this.router.queryParams.subscribe(params => {
        let options = { params: this.getHttpParams() }
        console.log(options)

        this.http.get<User>(`${this.serverUrl}`, options).subscribe(
            response => {
                this.user = response
                console.log(response)
            }
        ),
        console.log(params);
    })
}

Although getHttpParams function retrieves the correct values, the httpParams.append method is returning null within the HttpParams Map. Any suggestions on how to resolve this issue? Thank you!

Answer №1

The HttpParams append method will provide a new body with the added value.

fetchHttpParams = () => {
let httpParams = new HttpParams();
Object.keys(this.userForm.controls).forEach(key => {
  const value = this.userForm.get(key).value;
  if (value){
    httpParams = httpParams.append(key, value); // 👈
    console.log(httpParams)
  }

});
return httpParams;
}

Check out this article Creating a URL with HttpParams in Angular for further details

Answer №2

Creating an HttpParams object from another object is as easy as pie, just take a look at the code snippet provided:

generateHttpParams = () => new HttpParams({ fromObject: this.userDataForm.value });

Effortless and stylish!

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

Exploring the functionalities of React Native with react-hook-form and implementing them with TypeScript

I've been working on creating a custom Input component in react native using typescript for the react-hook-form library. type CustomInputProps = { name: any, control: any } const CustomInput: FC<CustomInputProps> = ({name, control, ...p ...

Having completed "npm link" and "npm i <repo>", the module cannot be resolved despite the presence of "main" and "types" in the package.json file

Here is the contents of my package.json file: { "name": "ts-logger", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "install": "tsc" ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

Using create-react-app with TypeScript for server-side rendering

My current project is built with create-react-app using typescript (tsx files). I'm now interested in implementing SSR for the project, but I'm not exactly sure where to begin. In the past, I've successfully implemented SSR with typescript ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

Error TS2339: The 'phoneType' property cannot be found on the 'Object' data type

Below is the declaration of an object: export class Card { private _phones:Object[] get phones(): Object[]{ if(this._phones === undefined) this._phones = [] return this._phones } set phones(val:Object[]){ ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

Disregarding TypeScript import errors within a monorepo ecosystem

In my Turborepo monorepo, I have a Next.js app package that imports various components from a shared package. This shared package is not compiled; it simply contains components imported directly by apps in the monorepo. The issue arises with the shared co ...

Guide for adjusting icon dimensions in Material-UI breakpoints

import { Container } from "@mui/material"; import * as React from "react"; import { Home } from "@mui/icons-material"; import PersonIcon from "@mui/icons-material/Person"; import FormatListBulletedIcon from "@mu ...

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...

Exploring a Firestore collection to extract data fields for storage and utilization

I'm currently facing a challenge while attempting to access my Firestore collection and iterate through all documents to extract the valenceId field in each document. Despite trying various approaches, I keep encountering an error message stating: "c ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

Error: Undefined object trying to access 'vibrate' property

Good day, I apologize for my poor English. I am encountering an issue with Ionic Capacitor while attempting to utilize the Vibration plugin. The documentation lacks detailed information, and when checking the Android Studio terminal, I found the following ...

Creating a Fixed HeaderToolbar in FullCalendar React

I am currently working on customizing the FullCalendar React component and I am looking to incorporate a sticky headerToolbar. My main objective is to have the header along with its toolbar remain fixed at the top of the calendar, even when users scroll th ...

How to Customize Bootstrap Colors Globally in Angular 4 Using Code

I am interested in developing a dynamic coloring system using Angular. I have set up a service with four predefined strings: success, info, warning, and danger, each assigned default color codes. My goal is to inject this service at the root of my applicat ...

Creation of Card Component with React Material-UI

I am facing difficulties in setting up the design for the card below. The media content is not loading and I cannot see any image on the card. Unfortunately, I am unable to share the original image due to company policies, so I have used a dummy image for ...

Implement the CSS styles from the Parent Component into the Child Component using Angular 6

Is there a way to apply CSS from the Parent Component to style the child component in Angular 6? Please advise on how to approach this issue. How can we inherit the css styles from the Parent Component? <parent> <child> <p>hello ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

What specific element is being targeted when a directive injects a ViewContainerRef?

What specific element is associated with a ViewContainerRef when injected into a directive? Take this scenario, where we have the following template: template `<div><span vcdirective></span></div>` Now, if the constructor for the ...