javascript - 是否可以在另一个请求中有一个 Angular js $http 请求?

标签 javascript html angularjs http angularjs-http

我正在尝试在 AngularJS 中发送请求以获取用于用户注册的 token 。获得 token 后,我将使用 token 发送另一个请求来注册用户。

然而,第一个请求有效并且我获得了 token ,但第二个请求无效。

代码

facebookExample.controller('registerController', function($scope, $http, $localStorage, $location) {
  $scope.data = {};
  $scope.getToken = function() {
      $http.post('http://you-serve.org/api.php?action=createaccount&format=json&name=' + $scope.data.username + '&email=' + $scope.data.email + '&realname=' +
        $scope.data.firstname + ' ' + $scope.data.lastname +
        '&mailpassword=false&reason=Fun_and_profit&language=en&token').then(
        function(response) {
          return response.data.createaccount.token;
        }
        // End success
        ,
        function() {
          alert('error');
        } // End error 
      ); //End then
    } // End getToken

  $scope.register = function(myToken) {
      $http.post('http://you-serve.org/api.php?    action=createaccount&format=json&name=' +
        $scope.data.username + '&email=' +
        $scope.data.email + '&realname=' +
        $scope.data.firstname + ' ' +
        $scope.data.lastname +
        '&mailpassword=false&reason=Fun_and_profit&language=en&token=' + myToken).then(
        function(response) {
          alert("Registration successful !  You can log in now " + response.data.createaccount.username);
        },
        function(response) {
          alert(response.data.error.info);
        }); //End then
    } //End register


  $scope.signup = function() {
      register(getToken);
    } // End sign up
}); // End controller
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<ion-view ng-controller="registerController" title="Sign Up" view-title="Sign Up" name="login-view">

  <ion-content class="padding">
    <div class="list list-inset">
      <label class="item item-input">
        <input type="text" placeholder="Username" ng-model="data.username">
      </label>
      <label class="item item-input">
        <input type="password" placeholder="Password" ng-model="data.password">
      </label>


      <label class="item item-input">
        <input type="text" placeholder="Email" ng-model="data.email">
      </label>


      <label class="item item-input">
        <input type="text" placeholder="First Name" ng-model="data.firstname">
      </label>

      <label class="item item-input">
        <input type="text" placeholder="Last Name" ng-model="data.lastname">
      </label>



      <label class="item item-input">
        <input type="text" placeholder="City" ng-model="data.city">
      </label>




      <label class="item item-input">
        <input type="text" placeholder="Country" ng-model="data.country">
      </label>
    </div>
    <button class="button button-block button-calm" ng-click="register(getToken())">Sign Up</button>
  </ion-content>
</ion-view>

有人知道我该怎么做吗?

最佳答案

您可以使用 promise1.then(promise2) 链接 promise (这是 $http 返回的内容)。

因此在您的情况下,链接 getToken 和注册的正确方法是:

$scope.getToken().then($scope.register)

(在您修改这两个函数以返回 $http 调用之后)

编辑:(进一步解释)

您尝试做的事情称为 promise 链。本质上,按顺序执行两个或多个异步操作。来自html5rocks promise tutorial :

Queuing asynchronous actions

You can also chain "then"s to run async actions in sequence.

When you return something from a "then" callback, it's a bit magic. If you return a value, the next "then" is called with that value. However, if you return something promise-like, the next "then" waits on it, and is only called when that promise settles (succeeds/fails).

它的工作方式是,当您从 Promise.then() 函数返回一个值时,链中的下一个 then 函数将被调用.then() 函数的返回值或 Promise 的解析,如果返回值为 Promise,那么链在继续之前等待此 Promise 解决。

因此(记住 $http 返回一个 Promise 对象):

function a() {
    return $http.get('...').then(function (response) { return response.data; });
}

function b(data) {
    return $http.get('...'+data).then(function (response) { return response.data; });
}

要将两个函数链接在一起,以便使用 a() 的结果调用 b(),只需执行以下操作:

a().then(b)

请阅读 the tutorial on Promises更好地了解它们的工作方式。它们是 JavaScript 使异步操作更易于处理的最佳工具之一。

PS:在您的具体情况下,代码为:

facebookExample.controller('registerController', function($scope, $http, $localStorage, $location) {
  $scope.data = {};

  function getToken() {
    return $http.post('http://you-serve.org/api.php?action=createaccount&format=json&name=' + $scope.data.username + '&email=' + $scope.data.email + '&realname=' + $scope.data.firstname + ' ' + $scope.data.lastname + '&mailpassword=false&reason=Fun_and_profit&language=en&token')
      .then(
        function(response) {
          return response.data.createaccount.token;
        },
        // End success
        function() {
          alert('error');
        } // End error 
      ); //End then
  } // End getToken

  function register(myToken) {
    return $http.post('http://you-serve.org/api.php?action=createaccount&format=json&name=' +
        $scope.data.username + '&email=' +
        $scope.data.email + '&realname=' +
        $scope.data.firstname + ' ' +
        $scope.data.lastname +
        '&mailpassword=false&reason=Fun_and_profit&language=en&token=' + myToken)
      .then(
        function(response) {
          alert("Registration successful !  You can log in now " + response.data.createaccount.username);
        },
        function(response) {
          alert(response.data.error.info);
        }
      ); //End then
  } //End register


  $scope.signup = function() {
    getToken().then(register);
  } // End sign up
}); // End controller

关于javascript - 是否可以在另一个请求中有一个 Angular js $http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252484/

相关文章:

javascript - phantomjs 中的代理

javascript - 从 Firefox 附加 SDK 的上下文菜单中打开一个新选项卡

javascript - 如何在 Ionic Framework 的操作表中使选项标签成为条件?

javascript - 在 AngularJS 中将值从 View 传递到 Controller

javascript - Webpack less-loader 在生产构建中缺少基本路径

html - 使用 rvest 在 r 中循环多个 url

javascript - html css 定位不起作用

html - 这可能吗?溢出-y :visible with overflow-x:scroll/auto

javascript - 使用 javascript 填写 pdf 表单(仅限客户端)

javascript - toLocaleString() 在货币和值之间有空格