Angularjs 首次注射不';不实例化

Angularjs 首次注射不';不实例化,angularjs,angularjs-factory,Angularjs,Angularjs Factory,第一次调用时,authenticated属性为false,即使凭证也正常。如果我用相同的凭证再次登录,就可以了 无论如何,我不确定我下面的工厂在angularjs是否正确。你能给我一些建议吗 工厂: 控制器: authenticator.trunt中的this.authenticated将在来自$resource的异步调用完成之前返回 在从工厂返回之前,以及在控制器中接收之前,您需要等待承诺得到解决 像这样的事情很可能会奏效: 工厂: authenticator.attempt = functi

第一次调用时,
authenticated
属性为
false
,即使凭证也正常。如果我用相同的凭证再次登录,就可以了

无论如何,我不确定我下面的工厂在angularjs是否正确。你能给我一些建议吗

工厂:

控制器:


authenticator.trunt
中的
this.authenticated
将在来自
$resource
的异步调用完成之前返回

在从工厂返回之前,以及在控制器中接收之前,您需要等待承诺得到解决

像这样的事情很可能会奏效:

工厂:

authenticator.attempt = function(email, password){

  var current = this;

  $resource("/service/authentication/:id", null, {'update' : { method: 'PUT'}})
    .save({'email' : email,'password': password},
      function(response){
          current.authenticated = sessionStorage.authenticated = true;
          current.userinfo = response.user;
          current.authenticated = true;
      },
      function(response){
          current.authenticated = false;
      }
    ).$promise.then(function () {
      return current.authenticated;
    });
};
控制器:

$scope.login = function() {

  var email = $sanitize($scope.email);
  var password = $sanitize($scope.password);

  authenticator.attempt(email, password).then(function(isAuthenticated) {

    if (isAuthenticated) $location.path('/dashboard');
    else alert.add("danger", "Login fail.");

  });
};

非常感谢,这很有帮助。
authenticator.attempt = function(email, password){

  var current = this;

  $resource("/service/authentication/:id", null, {'update' : { method: 'PUT'}})
    .save({'email' : email,'password': password},
      function(response){
          current.authenticated = sessionStorage.authenticated = true;
          current.userinfo = response.user;
          current.authenticated = true;
      },
      function(response){
          current.authenticated = false;
      }
    ).$promise.then(function () {
      return current.authenticated;
    });
};
$scope.login = function() {

  var email = $sanitize($scope.email);
  var password = $sanitize($scope.password);

  authenticator.attempt(email, password).then(function(isAuthenticated) {

    if (isAuthenticated) $location.path('/dashboard');
    else alert.add("danger", "Login fail.");

  });
};