Angular4 - 发布表格数据以休息api [英] Angular4 - post form data to rest api
问题描述
如何将表单数据发布到外部rest api?
How is it possible to post form data to an external rest api?
目前我有一个html表单:
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>
然后我有我在component.ts文件中处理提交的函数:
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);
}
但是如何将表单数据发布到我的外部API?使用angular发送表单数据的标准是什么?它只是一个简单的post请求,表单数据为queryParams,或者将其转换为JSON是标准的。我可以修改api来处理发送的数据,这不是问题。
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.
推荐答案
好的,所以事实证明我有添加.subscribe()来发布它做某事。
此外,如果我出于某种原因将用户直接放入发布请求中,它会发送一个请求,其中包含没有正文的方法OPTIONS。所以我必须自己创建一个queryParams字符串。如果任何人都可以解释这个或显示更好的方法来做到这一点,我会赞美它。否则这当前有效:
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:
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) => {});
}
编辑:另一个甚至更好的解决方案是使用JSON.stringify(用户)而不是body。但是仍然需要订阅()。
another and probably even a better solution is to use JSON.stringify(user) instead of body. But subscribe() is still needed tho.
这篇关于Angular4 - 发布表格数据以休息api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!