如何使用 angular 2 http post 函数使用 javascript 提交表单?
How to submit a form using angular 2 http post function using javascript?
我已经开始学习 Angular2
但我想使用 http.post()
将表单提交到我的网站 API 但我不能。
在您的组件中,您只需在 submit
事件上附加一个侦听器并利用 http
对象来执行 HTTP 请求。该对象之前被注入到组件的构造函数中。
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
:
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(Cmp, [ ng.http.HTTP_PROVIDERS]);
});
这里是对应的plunkr:https://plnkr.co/edit/Fl2pbKxBSWFOakgIFKaf?p=preview.
希望对你有帮助,
蒂埃里
我已经开始学习 Angular2
但我想使用 http.post()
将表单提交到我的网站 API 但我不能。
在您的组件中,您只需在 submit
事件上附加一个侦听器并利用 http
对象来执行 HTTP 请求。该对象之前被注入到组件的构造函数中。
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
:
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(Cmp, [ ng.http.HTTP_PROVIDERS]);
});
这里是对应的plunkr:https://plnkr.co/edit/Fl2pbKxBSWFOakgIFKaf?p=preview.
希望对你有帮助, 蒂埃里