简体   繁体   English

AngularJs许诺返回未定义

[英]AngularJs promise returns undefined

I'm trying to use the login function of my AuthService factory from my AuthLoginController controller. 我正在尝试从AuthLoginController控制器使用AuthService工厂的登录功能。 The problem is that when the User.login function is executed with a wrong email and password, the console.log() returns false which is what I want. 问题是当用错误的电子邮件和密码执行User.login函数时,console.log()返回false ,这就是我想要的。 But when i use the right email and password I'm getting a 但是,当我使用正确的电子邮件和密码时,

Error: response is not defined

I don't get it because everything works fine with function(error){ } but not with function(success){ } even though they are both the result of an asynchronous call. 我不明白,因为一切都可以通过function(error){}正常运行,但不能通过functionfunction(success){}正常运行,即使它们都是异步调用的结果。

angular
    .module('app')
      .factory('AuthService', ['Member', '$q', '$rootScope', '$state', function(
      User, $q, $rootScope, $state) {
    function login(email, password) {
  return User
    .login({email: email, password: password})
    .$promise
    .then(function(success) {
      $rootScope.currentUser = {
        id: response.user.id,
        tokenId: response.id,
        email: email,
        firstname: response.user.firstname,
        lastname: response.user.lastname
      };
      return true;
    },
    function(error) {
      return false;
    }
    );
}   return {
      login: login
    };
    }]);

Here is my AuthLoginController controller. 这是我的AuthLoginController控制器。

angular
  .module('app')
  .controller('AuthLoginController', ['$scope', 'AuthService', '$state',
      function($scope, AuthService, $state) {
    $scope.user = {
      email: 'test1@test.com',
      password: 'test1'
    };

    $scope.login = function() {
      AuthService.login($scope.user.email, $scope.user.password)
        .then(function(response) {
          console.log(response);
            return;
          }
          //go to the default state after login
          $state.go('test');
        });
    };
  }]);

How can I retrieve true from my AuthLoginController ? 如何从AuthLoginController检索true Thanks (Sorry for my bad english) 谢谢(对不起,我的英语不好)

.then(function(success) {
      $rootScope.currentUser = {
        id: **response**.user.id,
        tokenId: **response**.id,
        email: email,
        firstname: **response**.user.firstname,
        lastname: **response**.user.lastname
      };
      return true;
    },

The response variable is not defined in the "success" callback. 未在“成功”回调中定义响应变量。 "Success" argument variable should be used instead or it should be renamed to response probably. 应该改为使用“成功”参数变量,或者应该将其重命名为响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM