如何从异步POST请求返回字符串?

时间:2015-07-16 17:49:22

标签: javascript angularjs http

我尝试使用控制器和工厂向我的Angular应用添加一个注册功能,但我还没有能够获得多个字符串(有条件地成功或失败)返回从我的工厂到我的控制器。

下面的返回语句首先只返回空字符串(我假设这与异步http有关,但我不确定)。在任何情况下,我如何使用.success或.error中更新的值返回我想要的两个字符串(_alertType和_alertMessage)?

signup.html

<div class="col-md-6 container-fluid">

  <div class="jumbotron text-center" ng-controller="SignupController as vm">

    <p class="lead">
      <h2>Account Creation</h2>
      Welcome! Please make an account
    </p>

    <form ng-submit="vm.signup()">
      <p><input type="text" name="username" value="" placeholder="Username or Email" ng-model="username"></p>
      <p><input type="password" name="password" value="" placeholder="Password" ng-model="password"></p>
      <p class="submit"><input type="submit" name="commit" value="Sign Up"></p>
      <alert ng-show="vm.alertMessage" type="{{ vm.alertType }}">{{ vm.alertMessage }}</alert>
    </form>

  </div>

</div>

signup.factory.js

(function() {

  angular
    .module('app')
    .factory('signupFactory', signupFactory);

  signupFactory.$inject = ['$http'];

  function signupFactory($http) {
    var _alertType = '';
    var _alertMessage = '';
    var service = {
      signup: signup,
      getAlertType: getAlertType,
      getAlertMessage: getAlertMessage
    };
    return service;

    function signup(username, password) {

      var request = $http({
        method: 'POST',
        url: 'http://localhost:8080/user',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: {
          username: username,
          password: password
        }
      });
      request.success(function(){
        _alertType = "success";
        _alertMessage = "Signed Up";
      });
      request.error(function(){
        _alertType = "danger";
        _alertMessage = "Signup Failed";
      });
    }

    function getAlertType() {
      return _alertType;
    }

    function getAlertMessage() {
      return _alertMessage;
    }

  }

})();

signup.controller.js

(function() {
  'use strict';

  angular
    .module('app')
    .controller('SignupController', SignupController);

  SignupController.$inject = ['$scope', 'signupFactory'];

  function SignupController($scope, signupFactory) {
    var vm = this;
    vm.signup = function() {
      signupFactory.signup($scope.username, $scope.password);
      vm.alertMessage = signupFactory.getAlertMessage();
      vm.alertType = signupFactory.getAlertType();
    }

  }
})();

1 个答案:

答案 0 :(得分:3)

您应该寻找promises

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
});