Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4 - post form data to rest api

How is it possible to post form data to an external rest api?

At the moment i have an html form:

<form [formGroup] = "form" (ngSubmit) = "onSubmit(form.value)">
  <input name="name" formControlName="name">
  <input name="first_name" formControlName="first_name">
  <input name="last_name" formControlName="last_name">
  <button type="submit">Save</button>
 </form>

and then i have the function that is handling the submit in my component.ts file:

  onSubmit = function (user) {
    console.log(user);
    //this.http.post('http://xxx/externalapi/add', user);
  }

But how is it possible to post the form data to my external api? And what is the standard of sending form data with angular? Is it just a simple post request with form data as queryParams or is it standard to convert it into JSON. I can modify the api to handle whatever data is sent so thats not a problem.

like image 480
user1985273 Avatar asked Jun 14 '17 20:06

user1985273


1 Answers

How about using Typescript to make your life easier?

The html has ngModel two way binding.I've changed to rename the form personForm. You can add validation, but I have skipped it here.

 <form #personForm="ngForm"(ngSubmit)="onSubmit(personForm.value)">     
  <input name="firstName" [(ngModel)]="firstName">
  <input name="lastName" [(ngModel)]="lastName">
  <button type="submit">Save</button>
 </form>

On the component, you can use an interface Person which you can define in a models folder. The contents looks like this.

export interface Person {
  id:number;
  firstName: string;
  lastName: string;
}

And then in the submit method you can map it automatically like below.

onSubmit(person: Person){
  http.post('your_url', person).subscribe(status=> console.log(JSON.stringify(status)));
}

See how easy it is type safety? Also you can check if id is populated and either make a 'PUT' or 'DELETE' request depending on whether you want to update the person or delete.

like image 64
Mukus Avatar answered Oct 09 '22 20:10

Mukus