Javascript Angular4 - 将表单数据发布到 rest api

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44554353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:36:39  来源:igfitidea点击:

Angular4 - post form data to rest api

javascriptangulartypescript

提问by user1985273

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? 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.

但是如何将表单数据发布到我的外部 api?用angular发送表单数据的标准是什么?它只是一个简单的 post 请求,表单数据作为 queryParams 还是将其转换为 JSON 的标准。我可以修改 api 来处理发送的任何数据,所以这不是问题。

回答by GirishBabuC

For Making as generic Post& GetMethod 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); 
}

回答by user1985273

Ok, so it turns out i have to add .subscribe() to post for it to do something. Also if i put "user" straight into post request for some reason it sends an request with method "OPTIONS" without a body. So i have to create a queryParams string myself. If anyone can explain this or show a better way to do this i would appriciate it. Otherwise this currently works:

好吧,原来我必须添加 .subscribe() 来发布它才能做一些事情。此外,如果我出于某种原因将“用户”直接放入发布请求,它会发送一个带有方法“OPTIONS”的请求而没有正文。所以我必须自己创建一个 queryParams 字符串。如果有人可以解释这一点或展示一种更好的方法来做到这一点,我会很高兴。否则这目前有效:

 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. But subscribe() is still needed tho.

编辑:另一个甚至可能更好的解决方案是使用 JSON.stringify(user) 而不是 body。但是仍然需要 subscribe() 。

回答by Mukus

How about using Typescript to make your life easier?

如何使用 Typescript 让您的生活更轻松?

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

html 有ngModel两种方式绑定。我已更改为重命名表单 personForm。您可以添加验证,但我在这里跳过了它。

 <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.

在组件上,您可以使用可以在模型文件夹中定义的接口 Person。内容看起来像这样。

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.

看看类型安全有多容易?您还可以检查 id 是否已填充,并根据您是要更新人员还是删除人员来发出“PUT”或“DELETE”请求。

回答by israel

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

让我为接受的答案做出贡献,因为我没有足够的声誉来发表评论。您可以执行以下操作,而不是将所有表单 inputS 一一选择到模型中

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. I hope this simplifies the process for someone with a large form.

然后可以将这些值传递到您的 post 方法中。我希望这可以为大表单的人简化流程。