简体   繁体   中英

How to send form data to web api via Angular

I have a form in Angular 6 and I have a table which gets data from a web api. Is it possible to send that form data to that web api? I have a mock web api url which is a get request. My code so far is:

Html form:

    <form class="form-horizontal" [formGroup]="serviceForm" (ngSubmit)="onSubmit()">
<div class="form-group mb-8">
   <div class="col-3 col-sm-12">
      <label class="form-label" for="u_caller_id">On behalf of this user: <sub class="text-secondary">*</sub></label>
   </div>
   <div class="col-4 col-sm-12">
      <select formControlName="u_caller_id" class="form-select" required>
      <option *ngFor="let user of users" [ngValue]="user">
      {{ user.id }}
      </option>
      </select>
      <div *ngIf="serviceForm.get('u_caller_id').errors && (serviceForm.get('u_caller_id').touched || serviceForm.get('u_caller_id').dirty)">
         <div *ngIf="serviceForm.get('u_caller_id').hasError('required')" class="mt-2 mb-2">
            <h6 class="text-error">This field is required</h6>
         </div>
      </div>
   </div>
</div>
<div class="form-group mb-8">
   <div class="col-3 col-sm-12">
      <label class="form-label" for="u_destination_country">Your location: <sub class="text-secondary">*</sub></label>
   </div>
   <div class="col-4 col-sm-12">
      <select formControlName="u_destination_country" class="form-select">
      <option *ngFor="let state of countries" [ngValue]="state">
      {{ state.name }}
      </option>
      </select>
      <div *ngIf="serviceForm.get('u_destination_country').errors && (serviceForm.get('u_destination_country').touched || serviceForm.get('u_destination_country').dirty)">
         <div *ngIf="serviceForm.get('u_destination_country').hasError('required')" class="mt-2 mb-2">
            <h6 class="text-error">This field is required</h6>
         </div>
      </div>
   </div>
</div>
<div class="form-group mb-8">
   <div class="col-3 col-sm-12">
      <label class="form-label" for="u_requester_phone_number">Phone number: <sub class="text-secondary">*</sub></label>
   </div>
   <div class="col-4 col-sm-12">
      <input class="form-input" type="text" id="u_requester_phone_number" placeholder="Enter phone number" type="number"
         formControlName="u_requester_phone_number" required>
      <div *ngIf="serviceForm.get('u_requester_phone_number').errors && (serviceForm.get('u_requester_phone_number').touched || serviceForm.get('u_requester_phone_number').dirty)">
         <div *ngIf="serviceForm.get('u_requester_phone_number').hasError('required')" class="mt-2 mb-2">
            <h6 class="text-error">This field is required</h6>
         </div>
      </div>
   </div>
</div>
<div class="form-group mb-8">
   <div class="col-3 col-sm-12">
      <label class="form-label" for="u_serial_number">Device/Asset: <sub class="text-secondary">*</sub></label>
   </div>
   <div class="col-4 col-sm-12">
      <select formControlName="u_serial_number" class="form-select" required>
      <option *ngFor="let device of devices" [ngValue]="device">
      {{ device.id }}
      </option>
      </select>
      <div *ngIf="serviceForm.get('u_serial_number').errors && (serviceForm.get('u_serial_number').touched || serviceForm.get('u_serial_number').dirty)">
         <div *ngIf="serviceForm.get('u_serial_number').hasError('required')" class="mt-2 mb-2">
            <h6 class="text-error">This field is required</h6>
         </div>
      </div>
   </div>
</div>
<div class="form-group mb-8">
   <div class="col-3 col-sm-12">
      <label class="form-label" for="subject">Subject: <sub class="text-secondary">*</sub></label>
   </div>
   <div class="col-4 col-sm-12">
      <input class="form-input" type="text" id="subject" placeholder="Enter subject" type="text" formControlName="subject"
         required>
      <div *ngIf="serviceForm.get('subject').errors && (serviceForm.get('subject').touched || serviceForm.get('subject').dirty)">
         <div *ngIf="serviceForm.get('subject').hasError('required')" class="mt-2 mb-2">
            <h6 class="text-error">This field is required</h6>
         </div>
      </div>
      <h6 class="text-gray mt-2">Please note maximum length is 80 characters.</h6>
   </div>
</div>
<div class="form-group mb-8">
   <div class="col-3 col-sm-12">
      <label class="form-label" for="describe">Please describe your issue:</label>
   </div>
   <div class="col-4 col-sm-12">
      <textarea class="form-input" id="describe" placeholder="Describe your issue" rows="3" formControlName="issue"></textarea>
      <h6 class="text-gray mt-2">The more information you can provide here, the easier time the organization will
         have in diagnosing and resolving your issue.
      </h6>
   </div>
</div>
<div class="columns col-12 col-sm-12">
   <div class="column col-10 col-sm-6 text-right">
      <button class="btn btn-link">Cancel</button>
   </div>
   <div class="column col-2 col-sm-6">
      <!--<a routerLink="/incident">--><button class="btn btn-primary" type="submit">Submit</button><!--</a>-->
   </div>
</div>
</form>

TS file

onSubmit(serviceForm) {
    console.log("Service form submitted");
      var data = "u_caller_id=" + serviceForm.u_caller_id + "&u_destination_country=" + serviceForm.u_destination_country + "&u_requester_phone_number=" + serviceForm.u_requester_phone_number;
      this.http.post("https://demo1049220.mockable.io/api/incident", data).subscribe((data) => {});
      console.log("data has gone");
  }
}

service.ts (to get the web api data)

serviceApiUrl: string = 'https://demo1049220.mockable.io/api/incident';

  constructor(
    private http: HttpClient,

    ) { }

  public getAll() {
    return this.http.get(this.serviceApiUrl);
    }
  }

So I am a little confused on how to achieve this, any help would be great.

It seems you are trying to call onSubmit() but on your .ts file, you have onSubmit(serviceForm), since you are using a formGroup, you can get the values from that with "this.serviceForm.value", not pass to onSubmit function as an argument. So you can use it like this:

onSubmit() {
var data = "u_caller_id=" + this.serviceForm.value.u_caller_id + "&u_destination_country=" + this.serviceForm.value.u_destination_country + "&u_requester_phone_number=" + this.serviceForm.value.u_requester_phone_number;
this.http.post("https://demo1049220.mockable.io/api/incident", data).subscribe((res) => {});
console.log("data has gone");
}

This is the correct way to pass form values to your http request. Also name "data" can shadow result (data) from your subscription so change its name to something like (res) like I did.

On top of ts file, import "HttpHeaders" from "@angular/common/http":

import { HttpHeaders } from @angular/common/http;

Then update your onSubmit method like below:

onSubmit(){
   this.http.post("https://demo1049220.mockable.io/api/incident", 
      this.serviceForm.value,
      {
         headers : new HttpHeaders().set("Content-Type","application/json")
      }
   ).subscribe((response : any)=>{
       console.log(response);//On success response
   },(errorResponse : any)=>{
       console.log(errorResponse);//On unsuccessful response
   });
}

If the data has been sent successfully and server sends a successful response with 200 Ok, you will get a successful response in the first callback function, or else the second callback function will be called and your response will be in the "errorResponse" variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM