简体   繁体   English

Angular4-将表单数据发布到Rest API

[英]Angular4 - post form data to rest api

How is it possible to post form data to an external rest api? 如何将表单数据发布到外部Rest API?

At the moment i have an html form: 目前,我有一个HTML表单:

<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: 然后我有在我的component.ts文件中处理提交的功能:

  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? 但是如何将表单数据发布到我的外部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. 将表单数据作为queryParams只是一个简单的发布请求,还是将其转换为JSON的标准方法。 I can modify the api to handle whatever data is sent so thats not a problem. 我可以修改api以处理发送的任何数据,所以这不是问题。

For Making as generic Post & Get Method in angular 2/4 using form data 用于使用表格数据在角度2/4中作为通用PostGet方法进行制作

import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
import { Observable } from 'rxjs/Observable';

constructor(private _http: Http) { }

get(url: string): Observable < any > {
    return this._http.get(url)
             .map((response: Response) => <any>response.json()); 
}

post(url: string, model: any): Observable <any> {
    let formData: FormData = new FormData(); 
    formData.append('id', model.id); 
    formData.append('applicationName', model.applicationName); 
    return this._http.post(url, formData)
        .map((response: Response) => {
            return response;
        }).catch(this.handleError); 
}

Ok, so it turns out i have to add .subscribe() to post for it to do something. 好的,事实证明,我必须添加.subscribe()才能对其进行操作。 Also if i put "user" straight into post request for some reason it sends an request with method "OPTIONS" without a body. 另外,如果由于某种原因我直接将“用户”放入发布请求中,它会使用方法“ OPTIONS”发送没有正文的请求。 So i have to create a queryParams string myself. 所以我必须自己创建一个queryParams字符串。 If anyone can explain this or show a better way to do this i would appriciate it. 如果有人可以解释这一点或显示一种更好的方法来做到这一点,我会推荐它。 Otherwise this currently works: 否则,这当前有效:

 onSubmit = function (user) {
    console.log(user);

    var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&name=" + user.name;
    this.http.post("http://www.testtttt.com", body).subscribe((data) => {});

  }

Edit: another and probably even a better solution is to use JSON.stringify(user) instead of body. 编辑:另一个甚至可能更好的解决方案是使用JSON.stringify(user)代替body。 But subscribe() is still needed tho. 但是仍然需要subscribe()。

How about using Typescript to make your life easier? 如何使用Typescript使您的生活更轻松?

The html has ngModel two way binding.I've changed to rename the form personForm. html具有ngModel两种方式ngModel 。我已更改为将表单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. 在组件上,可以使用可以在models文件夹中定义的Person界面。 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. 然后,在Submit方法中,您可以像下面自动映射它。

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. 您还可以检查是否填充了id,并根据要更新此人还是要删除此人来进行“ PUT”或“ DELETE”请求。

Let me contribute to the accepted answer since I don't have enough reputation to comment. 由于我没有足够的声誉来发表评论,因此请允许我为已接受的答案做出贡献。 Rather than pick all the form inputS one by one into a model, you could do the following 您可以执行以下操作,而不是将所有表单输入一个接一个地放入模型中

var model = this.forContollname.value

Then you could call the following 然后您可以致电以下

 var values = JSON.stringify(model)

The values can then be passed into your post method. 然后可以将这些值传递到post方法中。 I hope this simplifies the process for someone with a large form. 我希望这可以简化大型表单的处理过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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