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

标签 javascript angular angular2-http

我已经开始学习 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/

相关文章:

javascript - meteor 铁路由器 : custom id route

javascript - Angular 2/4。我可以将函数绑定(bind)到 ngModel 吗?

angular - akka-http + angular2 路由

javascript - jQuery 数据表 : Use button to filter rows on all pages?

javascript - 使用边界条件检查二维数组中的附近点

javascript - 在用户不注意的情况下在特定滚动点打开网页,也不更改 URL

html - angular2中div的网格布局

angular - 从 Angular 2 中的 REST url 获取《英雄之旅》中的英雄

angular - CookieXSRFStrategy 在 AOT 模式下不工作 @angular

javascript - Angular 2 Http 轮询不传递错误