gpt4 book ai didi

javascript - 如何使用 javascript 使用 angular 2 http post 函数提交表单?

转载 作者:数据小太阳 更新时间:2023-10-29 03:49:47 26 4
gpt4 key购买 nike

我已经开始学习 Angular2,但我想使用 http.post() 向我的 Web API 提交表单,但我做不到。

最佳答案

在您的组件中,您只需在 submit 事件上附加一个监听器并利用 http 对象来执行 HTTP 请求。该对象之前被注入(inject)到组件的构造函数中。

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 .

希望对你有帮助,蒂埃里

关于javascript - 如何使用 javascript 使用 angular 2 http post 函数提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com