Ways to integrate user input into the header of an Angular HTTP post method

I need help figuring out how to incorporate user input into the header of a post method I am working with. I understand that some kind of binding is necessary, but I'm struggling to implement it in this case. Currently, I have a variable called postData which is hardcoded within the parameter, but I want this parameter to be determined by user input.

Below is the relevant section of my component.ts file:


export class AppComponent {

  value = '';
  update(value: string) { this.value = value; }
 

  postData ={ 
    name: "apple"
  } ; 

  getResults(postData){
    

    this.http.post<any>('APIUrlhere/issuerRestService/findIssuersBySearchCriteria', postData ).subscribe(data => {
    this.searchResult = data; 
    console.log(this.searchResult)
})

  }



}

The following snippet shows the HTML code where I capture user input labeled as "value":

<div>
        <label> Enter Company Name </label>
        <input #box
        (keyup.enter)="update(box.value)"
        (blur)="update(box.value)">
            
            <button (click)="getResults(postData)">Search</button>
           
        </div>

Any pointers on how to achieve this would be greatly appreciated. Thank you!

Answer №1

There are several ways you can handle this:

  1. Using JSON.stringify:
const data = JSON.stringify(postData);
return this.http.post('APIUrlhere/issuerRestService/findIssuersBySearchCriteria',
data, requestOptions);

This method sends the data in the request body.
2. Setting headers using http client

    const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
    let body = new HttpParams();
    body = body.set('postData', postData);
    this.http.post('APIUrlhere/issuerRestService/findIssuersBySearchCriteria', body, {
        headers: myheader});
  1. Request parameter
    var body = 'postdata=' + postData;
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http
      .post('APIUrlhere/issuerRestService/findIssuersBySearchCriteria',
        body, {
        headers: headers
      });

I recommend researching HTTP requests in Angular to learn more.
Here is a helpful link that explains Angular HTTP POST.


In the HTML file, instead of embedding the input value directly into the function, consider passing it as a parameter for better readability and maintainability.
<div>
    <label> Enter Company Name </label>
    <input #box
    (keyup.enter)="update(box.value)"
    (blur)="update(box.value)">
        
        <button (click)="getResults(box.value)">Search</button>
       
    </div>

Example with pure HTML and JavaScript:

var value = '';
  function update(value) { this.value = value; }
 

  var postData = { 
    name: "apple"
  }; 

  function getResults(postData){
alert(postData);

  }
<div>
        <label> Enter Company Name </label>
        <input #box id="box"
        (keyup.enter)="update(box.value)"
        (blur)="update(box.value)">
            <button onclick="getResults(box.value)">Search</button>
        </div>

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

Having trouble directing my attention towards a Mat card when using viewchildren in Angular

My current challenge is trying to focus on a specific card from a list of mat cards Despite my efforts, I keep encountering an error that reads: Cannot read property 'focus' of undefined Access the code on StackBlitz The desired functionali ...

Difficulty in dynamically changing Angular 6 directive attributes

I am currently working with component A, which features a custom directive on the web page: Here is how it looks: <warning [details]='details'></warning> The code for Component A is as follows: export class AComponent implemen ...

Identifying when an element is in or out of view using Next.js and TypeScript

I'm currently working on an app using Next and Typescript. The app features a navigation bar at the top of the screen, and I need it to change its style once it reaches a certain point in the view. I attempted to use jQuery for this purpose, but encou ...

Exploring the power of Angular and Module Federation in SSR applications

Currently, I am utilizing angular version 13.1.0 and have successfully set up SSR by using the ng add @nguniversal/common command. In addition to that, I integrated module federation through ng add @angular-architects/<a href="/cdn-cgi/l/email-protectio ...

Tips for Integrating an Angular App into a Different Website

I have an Angular application hosted at www.A.com, My client has a website hosted at www.B.com I am looking to enable my client to embed the Angular app on their webpage without physically copying the application files. I want them to simply add some HTML ...

How can I populate dropdown options from an API in a react JS project using typescript and react saga?

Check out my page, where I am trying to fetch brand options from an API. Below is the saga I have implemented: Action.tsx export const getBrandsForDropdown = (request: IPagination) => { return { type: actions, payload: request ...

Combining cells for certain entries in an Angular data table

Just starting to learn angular, and here's the scenario I'm dealing with: I have a table consisting of 10 columns. Let's say column 4 contains different status categories like children, teen, young, adult, and senior. When displaying all ...

The Angular filter feature operates on individual columns instead of filtering all columns simultaneously

Introduction I am currently working on implementing a feature in my Angular application where the column filter continuously updates the results based on the selected filters. The issue I'm facing is that when I select a filter in one column, it corr ...

Setting up webpack to compile just the necessary assets for running an Angular 5 application

I am currently using Angular 5 and I encountered a situation when running the following command: ng build --prod --named-chunks --aot This command generated numerous files and folders in the 'dist' directory: [development a85a7dc] Initial dist ...

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

The absence of a `require` definition in Typescript combined with daisyui

Considering using typescript with react and daisyUI (a tailwindCSS component). Just a heads up, I'm currently utilizing vite In my ts.config file, I've specified node as moduleResolution Encountering an error in the tailwind config stating &apo ...

Using injected services within static methods may seem tricky at first, but once you

I am exploring the integration of angularjs and typescript in my project. Currently, I am working on creating an Orm factory using typescript but have encountered some challenges. The structure of my factory class is as follows: class OrmModel implements ...

Ways to access nested keys in a TypeScript object as well as an array containing objects

As I develop a form generator, my goal is to achieve type safety for a nested object and an array of objects. Specifically, I want the 'name' property to correspond to the key of the respective object it belongs to. For instance, in the scenario ...

How to use Angular pipes to format dates as Long Dates in the template

Suppose I have a date input such as 2022-04-02T00:00:00. When I utilize {{data?.dateStarted | date:'MM/dd/YYYY'}}, the result will be 04/02/2022. But how can we transform it into a Long Date format like April 2, 2022? Does anyone have any sugges ...

The declaration of module 'DynamicTestModule' contains an unexpected value 'StateService'

In my Angular 5 project, I am using UI Router. While running tests for the footer component, I encountered the following error: Failed: Unexpected value 'StateService' declared by the module 'DynamicTestModule'. Please add a @Pipe/@Dir ...

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...

Geolocation plugin in Ionic encountered an issue: "Geolocation provider not found"

I've been working on implementing geolocation in my ionic2 hello world project, and I successfully added the ionic plugin called "Geolocation" by following the instructions on the official website. After running these two commands: $ ionic plugin add ...

Angular searchbar issue: Unable to assign parameter of type 'unknown' to parameter of type 'string'

I've been working on an Angular app to fetch data from an API successfully. However, I'm currently facing a challenge while implementing a search function in my component.ts file. Here is the entire service code: import { Injectable } from &apos ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...