如何使用角度捕获数据并发送到服务器 API

How to capture data and send to server API using angular

本文关键字:并发 服务器 API 数据 何使用      更新时间:2023-09-26

我是第一次使用 Angular,在将简单数据发送回服务器时遇到了问题。

我有一个在 API: http://localhost:8080/takepayment 上运行的服务器,它接受POST请求并期望tokenId.

我的 JS 看起来像这样,并且成功从 Stripe 取回了一个令牌。我只想将此令牌作为POST请求发送到上述 API URL。

如何在 Angular 中执行此操作?

'use strict';
angular.module('angularDjangoRegistrationAuthApp')
.controller('TakeMoneyCtrl', function ($scope, djangoAuth, Validate) {
  $scope.complete = false;
  djangoAuth.profile().then(function(data){
    $scope.model = data;
  });
  $scope.handleStripe = function(status, response){
    if(response.error) {
      // there was an error. Fix it.
      alert("error")
    } else {
      // got stripe token, now charge it or smt
      token = response.id
      alert("success: " +token);
    }
  }
});

我想仅在成功从 Stripe 取回令牌时才将令牌发送到服务器。所以我在那里放了一个alert("success");,但即使是那个警报也没有显示在页面上。alert("error");也没有显示。但是,在chrome的网络选项卡上,我可以看到token实际上是从条纹返回的。

问题

如何将从 Stripe 获取的令牌作为POST请求发送到我的 API 调用http://localhost:8080/takepayment/

您需要

使用 Angular $http 服务(此处为文档)。注入它,然后在控制器中使用它。下面是一个简单的示例,它使用 Angular $http 服务并执行POST

angular.module('angularDjangoRegistrationAuthApp')
.controller('TakeMoneyCtrl', ['$http', function ($scope, $http, djangoAuth, Validate) {
  $scope.complete = false;
  djangoAuth.profile().then(function(data){
    $scope.model = data;
  });
  $scope.handleStripe = function(status, response){
    if(response.error) {
      // there was an error. Fix it.
      alert("error")
    } else {
      // got stripe token, put it in an object then use it in $http.post
      var dataModel = {
         token: response.id
      };
     //You can do your $http post here OR preferably in Seperate Service.
     $http.post('/someUrl', JSON.stringify(dataModel)).
      success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
      alert("success: " +token);
    }
  }
}]);

以上是一种方法。但最好将$http调用移动到单独的 Angular 服务中,并可能使用 JS Promise 来等待响应或超时发生。下面是一个服务和使用 Promise 进行 HTTP 发布的示例。

创建一个新的 Angular 服务来处理$http

var app = angular.module('angularDjangoRegistrationAuthApp', []);
app.service('CommService', ['$http', function ($http) {
    this.processLoginToken = function(token) {
        var model = {
            token: token
        };
        var promise = $http.post('/api/tokenproc', JSON.stringify(model))
            .then(function(response) {
                return response.data;
            }, function(error) {
               console.log("Communication error, server did not reply.");
            });
        return promise;
    };

现在,在您的服务之外,您将像这样使用它。

   var token = "02394924924929424";
   CommService.processLoginToken(token)
    .then(function (response) {
           //Process your response.data here
        }, function () {
           //Server didn't respond.
    });