How to submit a form using angular 2 http post function using javascript?

不打扰是莪最后的温柔 提交于 2019-12-23 07:38:40

问题


I've started to learning Angular2 but I want to submit a form using http.post() to my Web API but I can't.


回答1:


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');
      });
    }
  });

You need to add the HTTP_PROVIDERS when bootstrapping your application:

document.addEventListener('DOMContentLoaded', function() {
  ng.platform.browser.bootstrap(Cmp, [ ng.http.HTTP_PROVIDERS]);
});

Here is the corresponding plunkr: https://plnkr.co/edit/Fl2pbKxBSWFOakgIFKaf?p=preview.

Hope it helps you, Thierry



来源:https://stackoverflow.com/questions/35088479/how-to-submit-a-form-using-angular-2-http-post-function-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!