如何使用JavaScript在AngularJS 2.0中调用Restful API

How to Call Restful API in AngularJS 2.0 using JavaScript?

本文关键字:调用 Restful API 何使用 JavaScript AngularJS      更新时间:2023-09-26

我有一些表单的示例代码,现在我想将这些数据发布到Restful API。我检查了很多,但大部分都是基于TypeScript的结果。我想只使用JavaScript。有没有什么方法可以使用JavaScript来做到这一点?

我想在"onSubmit"事件上调用Postneneneba API。查看示例代码。

(function(app) {
  app.FormComponent = ng.core
    .Component({
      selector: 'form',
      templateUrl: 'app/form.component.html'
    })
    .Class({
      constructor: function() {      
      },
      onSubmit: function() {
        console.log(this.model);
        this.submitted = true;
      },
    });
})(window.app || (window.app = {}));

您可以使用fetch进行服务器调用:

(function(app) {
app.FormComponent = ng.core
    .Component({
    selector: 'form',
    templateUrl: 'app/form.component.html'
    })
    .Class({
    constructor: function() {},
    onSubmit: function() {
        console.log(this.model);
        this.submitted = true;
        const url = 'http://example.com';
        fetch(url, {
            method: 'POST',
            body: this.model
            //new FormData(document.getElementById('inputform'))
            // -- or --
            // body : JSON.stringify({
            // user : document.getElementById('user').value,
            // ...
            // })
            })
        .then(
            response => response.text() // .json(), etc.
            // same as function(response) {return response.text();}
        )
        .then(html => console.log(html));
    }
    });
})(window.app || (window.app = {}));

如中所示https://stackoverflow.com/a/45529553/512089