如何使用javascript提交使用angular 2 http post功能的表单? [英] How to submit a form using angular 2 http post function using javascript?
问题描述
我已经开始学习 Angular2
但我想使用 http.post()
提交表单我的Web API,但我不能。
I've started to learning Angular2
but I want to submit a form using http.post()
to my Web API but I can't.
推荐答案
在你的组件中,你只需要在<$ c上附加一个监听器$ c>提交事件并利用 http
对象来执行HTTP请求。此对象先前已注入组件的构造函数中。
Within your component, you simply need to attach a listener on the submit
event and leverage the http
object to execute the HTTP request. This object was previously injected into the constructor of the component.
var Cmp = ng.core.
Component({
selector: 'cmp'
template: `
<form (submit)="submitForm()">
<input [(ngModel)]="element.name"/>
<button type="submit">Submit the form</button>
</form>
`
}).
Class({
constructor: [ ng.http.Http, function(http) {
this.http = http;
}],
submitForm: function() {
var headers = new ng.http.Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://...', JSON.stringify(this.element), {
headers: headers
}).subscribe(function(data) {
console.log('received response');
});
}
});
您需要在引导时添加 HTTP_PROVIDERS
你的申请:
You need to add the HTTP_PROVIDERS
when bootstrapping your application:
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(Cmp, [ ng.http.HTTP_PROVIDERS]);
});
这是相应的plunkr: https://plnkr.co/edit/Fl2pbKxBSWFOakgIFKaf?p=preview 。
Here is the corresponding plunkr: https://plnkr.co/edit/Fl2pbKxBSWFOakgIFKaf?p=preview.
希望它可以帮到你,
Thierry
Hope it helps you, Thierry
这篇关于如何使用javascript提交使用angular 2 http post功能的表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!