角度承诺(承诺?)。或者如何在角度$ http.success之后链接.then

时间:2014-05-17 16:43:35

标签: javascript angularjs promise

我在Angular获得了一项服务:

App.factory('AuthService', function ($q, $http, CredentialStorage) {
  var _endpoint = 'http://localhost:3000';
  return {
    login: function (credentials) {
      return $http
        .post('/api/users/login', credentials)
        .success(function (apiResult) {
          var deferred = $q.defer();

          if (apiResult.code == 0) { 
            $scope.user = apiResult.context;
            CredentialStorage.store(apiResult.context);
          }

          return deferred.promise;
        })
        .fail(function(apiResult, status, headers) {
          var deferred = $q.defer();
          return deferred.promise;
        });
    },
....});

我在哪里验证并将用户存储在某个cookie或其他任何内容中(这是不相关的)。

然后在我的控制器上我得到了:

App.controller('LoginController', function ($scope, $rootScope, AuthService) {
    var _login = function($event) {
        $event.preventDefault();

        AuthService.login($scope.l).then(function() {
            alert('aaa');
            if (!AuthService.authenticatedUser) {
                $scope.errors = ['Invalid username and password. Please try again.'];
                alert($scope.errors);
            } else {
                alert('a' + $scope.errors);
            }
        })
    }
    $scope.login = _login;
});

由于某种原因,我的控制器不会执行。那是为什么?

由于

1 个答案:

答案 0 :(得分:1)

嗯,简单的答案是:你使用.then代替success而不是App.factory('AuthService', function ($q, $http, CredentialStorage) { var _endpoint = 'http://localhost:3000'; return { login: function (credentials) { return $http .post('/api/users/login', credentials) .then(function (response) { var apiResult = response.data; if (apiResult.code == 0) { CredentialStorage.store(apiResult.context); return apiResult.context; // promises let you return the value } throw new Error("Authentication failed"); // return $q.reject // if you don't want to invoke // exceptionHandler }); }, ....}); 只添加一个监听器:

   AuthService.login($scope.l).then(function(result) {
        $scope.user = result;
   }).catch(function(err){
        // code to handle the case authorization failed or the API call failed
   });

可以让你这样做:

{{1}}

从关注角度的角度分离来看,修改服务/工厂/提供商中的UI范围通常是不好的。最好返回结果。