9

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

4

1 回答 1

11

在您的组件中,您只需在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 。

希望它可以帮助你,蒂埃里

于 2016-01-29T16:12:00.587 回答