9

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

John Hascall
  • 9,176
  • 6
  • 48
  • 72
Nazmus Sakib
  • 105
  • 1
  • 1
  • 4

1 Answers1

11

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

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • 1
    Thanks bro...It's working...actuality i am learning `angular 2` and there are not much resource about `anguler 2` on `javascript` so i got many problem which i can't solve. – Nazmus Sakib Jan 29 '16 at 17:24
  • You're welcome! I know that Angular2 team works on this but best pratices at this level don't seem to be clear enough ;-) – Thierry Templier Jan 29 '16 at 17:28
  • if you don't mind do you have any idea where i learn basic `angular 2` in `javascript` language ? without [angular.io] website – Nazmus Sakib Jan 29 '16 at 20:58
  • I would quote these two following ones: http://blog.thoughtram.io/angular/2015/05/09/writing-angular-2-code-in-es5.html and http://blog.thoughtram.io/angular/2015/07/06/even-better-es5-code-for-angular-2.html. Otherwise you can have a look directly within the `angular2-all.umd.dev.js` file. You can notice that TypeScript-based samples can also help you because you have the same concepts in JavaScript... – Thierry Templier Jan 30 '16 at 15:02