1
votes

I have two type of Request that I need to fetch from the Angular UI page and pass it into app.component.ts file so that I can call my REST client through HTML page.

Request 1:

End Point: (GET call)

  http://localhost:8081/api/products?productId=7e1308ba2b9af

I just created a text field in the app.component.html file as like below:

    <div>
      <input type="text" placeholder="Product ID" class="user_id_text"/>
    </div>
    <div>
      <input type="submit" value="submit"/>
    </div>

Output:

enter image description here

I have written the below code and ensured it works as expected by using the hard-coded value.

app.component.ts:

 ngOnInit():void{

    this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{ 

      console.log(data);
    });
  }

The above code return data array with proper response. But the above productId value is hard-coded (7e1308ba2b9af). And I just want to get that value from HTML text box when user click the submit button and pass it to query param and run the above request.

Request 2:

I have to get the below format json file from text box and pass it as JSON request body to the below end point URL.

End Point: (PUT call)

    https://localhost:8081/api/updateRecord

Request JSON:

{
  "productId":234242882,
  "purchaseDate" : "2019-12-20",
  "status": "dispatched"
}

I just want to create a text field and get the above json file if user click submit button and invoke the above end point.

I'm very new to the Angular and not sure how to implement this. I just googled but I didn't understand the way they resolved. It would be much appreciated if someone explain me the things and guide me to resolve this.

3

3 Answers

1
votes

for request 1:

put a id to your input tag and then try this:

let variableValue = (<HTMLInputElement>document.getElementById("idproduct")).value

or

let variableValue = document.getElementById("idproduct").innerHTML
1
votes

Request 1

We can use ReactiveFormsModule to allow us to get the value from user input directly and then feed it dynamically to the api.

We also need to import HttpClientModule

To achieve this:

app.module.ts

import {ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [...],
imports: [...,ReactiveFormsModule, HttpClientModule],
providers: []...

After you have imported ReactiveFormsModule,and HttpClientModule we can now use FormBuilder and FormGroup to allow us to dynamically keep track of user input and HttpClient to send get requests to our api.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';




@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
   productIDForm: FormGroup;
    httpHeaders: new HttpHeaders({
      'Content-Type': 'application/json',
   })
   constructor(
     private formBuilder: FormBuilder,
     private http: HttpClient
   ) { }



ngOnInit() {
     this.productIDForm = this.formBuilder.group({
       'productID': [null, [Validators.required, Validators.nullValidator]]
    })
  }

 onSubmit() {
if (this.productIDForm.invalid) return;

this.getProduct(this.productID.get('productID').value).subscribe(
  (res) => {
    console.log(res);
// If the request was successful then `res` contains the information about the product.
  },
(err) => {
  console.log(err);
// If the request failed, `err` contains the information why the failure occured
 )
 }



getProduct(productID: string): Observable<any> {
        return this.http.get(
          `http://localhost:8081/api/products?productId=${productID}`,
       { headers: this.httpHeaders }

       )
    }
}

We now need to bind the input field to productIDForm.

app.component.html

<form [formGroup]="productIDForm">
      <input formControlName="productID" type="text" class="user_id_text"/>
    </form>
    <div>
      <input (click)="onSubmit()" type="button" />
    </div>

Request 2

We still use the ReactiveFormsModule, FormBuilder and FormGroup to dynamically fetch the user input and sort of bind it to the api PUT request.

app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs';


    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {

    productIDForm: FormGroup;
        httpHeaders: new HttpHeaders({
          'Content-Type': 'application/json',
       })

   constructor(
     private formBuilder: FormBuilder,
     private http: HttpClient
   ) { }



ngOnInit() {
     this.productDetailsForm = this.formBuilder.group({

'productID': [null, [Validators.required, Validators.nullValidator]],
'purchaseDate': [null, [Validators.required, Validators.nullValidator]],
'status': [null, [Validators.required, Validators.nullValidator]]
})

}


onSubmit() {

    if (this.productDetailsForm.invalid) return;
    let recordNewDetails = {
        "productId": this.productDetailsForm.get('productID').value,
        "purchaseDate": this.productDetailsForm.get('purchaseDate').value,
        "status": this.productDetailsForm.get('status').value
    }
  recordNewDetails = JSON.stringify(recordNewDetails); // This will format `recordNewDetails` to JSON format.

this.updateRecord(recordNewDetails).subscribe(
  (res) => {
    console.log(res);
// If the request was successful then `res` contains the information about the product.
  },
(err) => {
  console.log(err);
// If the request failed, `err` contains the information why the failure occured
 )
 }

updateRecord(productDetails: {}): Observable<any> {
        return this.http.put(
          `https://localhost:8081/api/updateRecord`m
           productDetails,
          { headers: this.httpHeaders }

       )
    }
}

app.component.html

<form [formGroup]="productDetailsForm">
      <input formControlName="productID" type="text" class="user_id_text"/>
<input formControlName="purchaseDate"  type="date">
<select formControlName="status">
    <option disabled>Select Status Option</option>
    <option>Dispatched</option>
  </select>
    </form>

    <div>
      <input (click)="onSubmit()" type="button" />
    </div>
0
votes

Use [(ngModel)] to bind an input to a variable:

<div>
  <input type="text" [(ngModel)]="productId" placeholder="Product ID"
         class="user_id_text"/>
</div>

Use (click) to bind a button to a function:

<div>
  <input type="submit" (click)="getById(productId)" value="submit"/>
</div>

In the controller:

ngOnInit():void {    
    this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{     
      console.log(data);
    });
}

getById():void {
    const base:string = "http://localhost:8081/api/products";       
    const url:string = `${base}?productId=${this.productId}`;
    this.http.get(url).subscribe(data =>{ 
        console.log(data);
    });    
}