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

Invoke the API when the value of a property in the SPFX property pane is modified

Here's a question that might sound silly, but I'll ask anyway. I have a dropdown field in my Property pane that is filled with all the lists from the current site. It's working fine. When I change the dropdown selection, it populates a pro ...

Pressing a button that appears multiple times and is also embedded within layers

I am facing an issue where I need to interact with a button that appears multiple times on the website within nested cards. Specifically, I am trying to locate the card containing a pet named Bala, as shown in the attachment below, and click on the Detail ...

How to remove the border of the MUI Select Component in React JS after it has been clicked on

I am struggling to find the proper CSS code to remove the blue border from Select in MUI after clicking on it. Even though I managed to remove the default border, the blue one still persists as shown in this sandbox example (https://codesandbox.io/s/autumn ...

Dealing with Angular can be frustrating at times, especially when you encounter errors like "TypeError: Cannot

Encountering an Error Message... ERROR TypeError: Cannot read properties of undefined (reading 'geoCoord') at Object.next (customers.service.ts:16:38) When assigning fixed values to "lon" and "lat" variables, like 51.1634 and 10.4477, the f ...

Angular nested router causing an infinite loop

I am currently working on creating a basic webpage layout consisting of a header, menu, and content div. My goal is to have the content div populate with the corresponding page when a user clicks on a link in the menu. Currently, I just want this common la ...

Ways to make the input field appear invalid without the use of forms, causing the bottom outline to turn red when a specific condition is met

Currently, the application does not utilize any forms. I am interested in making the input field invalid under certain conditions within the component. For example, if a user leaves the input field blank, I would like the bottom outline to turn red when an ...

Height transition animation in Angular 2 - maintaining state consistency

I am currently working with an animation code that is linked to my component. animations:[ trigger('slide', [ state('show', style({ height: '*' })), state('hide ...

Angular 2: Making POST Requests

I have encountered a peculiar issue with Angular 2 HTTP post requests. public post(_ApiUrl: string, _Body: string): Promise<any> { let token = this.storage.getauthToken(); const headers = new HttpHeaders().set("Content-Type", "application/j ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Defining assertions with specified type criteria

Looking to do something special in TypeScript with a class called Foo. I want to create a static array named bar using const assertion, where the values are restricted to the keys of Foo. This array will serve as the type for the function func while also a ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Using Angular to declare a variable for reuse within nested HTML elements

Exploring the realm of angular development has sparked my interest, however, I found myself at a roadblock while reading through the documentation. The issue lies in figuring out how to declare a variable that can be reused effectively within nested HTML e ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

The language in the React Native app remains unchanged despite utilizing i18next.changeLanguage

I am currently attempting to integrate the i18next library into my React Native app in order to facilitate language changes, but I have encountered difficulties with translation. image description here I have created an i18n.tsx file. import i18next from & ...

Is there a way to conceal an element within a component based on the current component being used with the router?

I have managed to hide an entire component, but I am unsure of how to show or hide specific elements within a component. export class AppComponent { headerFooterVisible: boolean; constructor(private router: Router) { router.events.subscribe(e =&g ...

Tips for capturing your desktop screen within an angular 2+ application

I am in need of a solution to share my desktop screen using Angular 6. I have done some research to find the right package for this feature but have been unsuccessful so far. I came across various packages such as RecordRTC, Aperture, and screen-capture-r ...

When trying to reload Angular 8 pages, encountering an error that reads "Cannot GET /login" and also receiving a notification stating the image '/favicon.ico' cannot be loaded due to a violation of

Encountering an issue with the error message "Cannot GET login/" appearing on the page body of my latest Angular 8 app. Despite attempting various solutions found on forums, I have been unable to resolve this error. Any suggestions or advice would be great ...

When a module with routes is imported into another module with lazy-loading, the routing system becomes disrupted

Within our angular application running version 4.3.6, we have implemented lazy-loaded modules such as Fleet, Maintenance, and Car. Examining our primary app router structure: const routes: Routes = [ { path: '', redirectTo: 'fleet', ...

Navigating to the HomePage using the nebular auth/login library with the login() function: A step-by-step guide

After setting up my Angular Project and installing the nebular library, I am working on creating 3 pages: Login, Register, and Home. I have successfully created the login and register pages using NbLoginComponent and NbRegisterComponent. Now, my goal is to ...