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

Unusual actions observed in Ionic 3 app using webview 3 plugin

I am currently facing a significant problem with Webview 3. One of our developers upgraded it to webview 3 without utilizing the Ionic native webview plugin, and surprisingly, it is functioning well on our Ionic 3 application. As per the documentation avai ...

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

There was an issue with matching the call for formatting the start date to "dd MMMM yy" in the function

Hey there, while deploying my project, I encountered this error: Error: No overload matches this call. Overload 1 of 4, '(value: string | number | Date): Date', resulted in the following error: Argument with type 'string | string[] | ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

No control access origin header found on the request to Spring 5 WebFlux functional endpoints

I have scoured numerous resources in search of the perfect solution to my issue. In my opinion, I believe I have all the necessary components in place but I am unable to pinpoint where the problem lies. Utilizing spring 5 with WebFlux and functional endpo ...

What is the best way to extract information from an observable stream?

Within my codebase, there exists an observable that I have defined as: public selectedObjectsIds$ = of(); In addition, there is another stream present: this.reportMode$.pipe( filter((state: ReportMode) => state === ReportMode.close) ) .subscribe(() ...

The in-memory-web-api is failing to respond to queries when using Chrome

I've been experiencing an issue with my in-memory database setup. Even though I have registered everything correctly, I am not receiving any data back. There are no errors or 404 responses; it seems like the app is intercepting the request and returni ...

Guide on retrieving data parameter on the receiving page from Ajax response call

I am working on dynamically opening a page using Ajax to avoid refreshing the browser. The page opens and runs scripts on the destination page, but before running the script, I need to retrieve parameters similar to request.querystring in JavaScript. Belo ...

Ways to implement es6 in TypeScript alongside react, webpack, and babel

Being new to front-end development, I have found that following a simple tutorial can quickly help me start tackling problems in this field. One issue I've encountered is with ES5, which lacks some of the tools that are important to me, like key-value ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Error encountered while importing AgGridModule in Angular2: Unexpected token

I'm facing an issue while trying to integrate ag-grid into my Angular2 project. Whenever I include AgGridModule in the @NgModule imports, it triggers an error message: (SystemJS) Unexpected token at eval import { AgGridModule } from 'ag-grid-ang ...

Is there a way to replace mat-button-toggle with a radio button?

Hey there, I am just starting with Angular and I'm looking to transform the code below into radio buttons. <div class="col-4"> <div class="label-icon"><label><b>Certfication Required</b></label> </div&g ...

What is the best way to host a single page application within a sub-directory using nginx?

Trying to set up nginx to host an Angular application from a unique child path. Adjusted the app to use a base href of fish, able to serve root page and assets correctly. However, encountering a 404 error when attempting to reload the page on a child rout ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

Sharing markdown content between two Vue.js components

I have a markdown editor in View A which is displaying the result in the current View. My goal is to share this result with another page, View B. In View A, there is a button that allows the user to share the markdown result with View B. I am using a texta ...

Troubleshooting dynamic route issues in Angular 6 when making changes in *ngFor

`<div *ngFor="let data of projects"> <a [routerLink]="'/projects/'+data.project_id"> {{data.project_name}}</a> </div>` When I click on the link, the URL changes from http://localhost:4200/projects/1 to http://localhost ...

What are the benefits of incorporating a proxy.conf.json file into an Angular application?

Imagine we have a server running on http://localhost:8080/. Rather than configuring the back-end's base URL from environment.ts file, we can create a proxy.conf.json file with the code below: { "/api": { "target": "http://localhost:8080", ...

How can we recreate this ngModel text input form in a radio format for a spring boot mvc and angular application?

As I was following a tutorial on creating an employee CRUD model using spring boot and mysql server for the backend and angular for the frontend, I encountered a form group during the creation process. The tutorial originally had a text input field for gen ...

Understanding the significance of an exclamation point preceding a period

Recently, I came across this code snippet: fixture.componentInstance.dataSource!.data = []; I am intrigued by the syntax dataSource!.data and would like to understand its significance. While familiar with using a question mark (?) before a dot (.) as in ...

How can I store unique and only selected checkbox values in an array using Angular?

I need assistance with creating an array from three checkboxes. The array should only contain the values of the checked checkboxes and should not include duplicates. I have attempted to achieve this functionality, but the values are still being added rega ...