AngularJS工厂返回undefined

时间:2015-12-21 17:48:45

标签: angularjs

几个星期前我开始使用AngularJS编程。我想创建我的第一家工厂,但我对发生的事情感到困惑。

工厂:

var services =angular.module('services', ['ngResource']);

services.factory('UserSession',['$resource',function($resource) {
  var user = {};
  var loggedIn = false;
  var details={initstate:'for demo purpose'};

  user.authenticate = function(uname,pwd) {
    var apiauthentification = $resource('/api/authenticate');
    var tmp={
        username:uname,
        password:pwd
    };

    var auth = apiauthentification.save(tmp, function(){
        console.log(auth);
        if (auth.success){
            isLoggedIn=true;
        }
        details=auth;
    })
  };

  user.getDetails = function(){
    return details;
  };

  user.isLoggedIn = function() {
    return loggedIn;
  };


  return user;
}]);

控制器:

app.controller('LoginCtrl',['$scope','$resource','$location','UserSession',function($scope,$resource,$location,UserSession){

  $scope.login = function (){
    var tmp = UserSession.authenticate($scope.username,$scope.password);
    console.log('UserSession.isLoggedIn():'+UserSession.isLoggedIn());
    console.log ('Result authenticate:'+tmp);
    console.log('UserSession.getDetails():');
    console.log(UserSession.getDetails());
  };
}]);

的login.html

<h3>Login page</h3>
<form>
    <label>Username</label>
    <input class="form-control" name="username" ng-model="username" required></input>

    <label>Password</label>
    <input class="form-control" name="password" ng-model="password" required></input>

    <button ng-click="login()">
        Test login
    </button>



    <label>result</label>
    <input class="form-control" name="loginresult" ng-model="logresult"></input>

</form>

控制台:

UserSession.isLoggedIn():false

Result authenticate:undefined

UserSession.getDetails():

Object {initstate: "for demo purpose"}

g {success: false, msg: "Authentification failed. User not found", $promise: d, $resolved: true}

    $promise: d

    $resolved: true

    msg: "Authentification failed. User not found"

    success: false

    __proto__: g

问题:

  

1-为什么我的tmp变量未定义?

     

2-我想我需要使用回调函数但是如何设置呢?

1 个答案:

答案 0 :(得分:0)

1 - 定义了tmp变量,因为您没有在authenticate方法中返回任何内容。

2 - 您可以在authenticate方法中使用回调函数,如下所示:

user.authenticate = function(uname, pwd, callback) {
    var apiauthentification = $resource('/api/authenticate');
    var tmp = {
        username:uname,
        password:pwd
    };

    apiauthentification.save(tmp, function (response) {
        if (response.success){
            isLoggedIn=true;
            details=auth;
            return callback({success: true});
        }
        return callback({success: false});
    });
};

然后这样称呼:

UserSession.authenticate($scope.username,$scope.password, function (success) {
    // This code will be executed once authenticate method has finished
    if(success) {
        console.log('User authenticated');
    }
});

您可能需要对此代码进行一些调整以满足您的需求。