2013-07-22 45 views
0

我在使用服務對外部API進行身份驗證時遇到問題,並將更新的服務數據註冊到同一表單提交中。我很確定這是一個範圍問題,但我對角度很陌生,並且不確定如何在控制器中正確地確定範圍。基於xhr的angularjs服務更新

我已經定義了以下AUTH服務:

angular.module('myapp.services', []). 
    factory('AuthService', ['$http', function($http){ 
    var currentUser; 
    var isLoggedIn = false; 

    return { 
     login: function(user, pass) { 
     $http({method: 'GET', url:'https://some-api/api/login/'+user+'/'+pass}). 
      success(function(data){ 
      currentUser = data; 
      isLoggedIn = true; 
      }); 
     }, 
     isLoggedIn: function(){ return isLoggedIn; }, 
     currentUser: function(){ return currentUser; } 
    }; 
    }]); 

我然後在綁定到「用戶」的圖的基本方式,然後在我的控制器:

angular.module('myapp.controllers', []) 
    .controller('LoginCtrl', ['$scope', 'AuthService', function(scope, AuthService) { 
    scope.update = function(user){ 
     AuthService.login(user.username, user.password); 
     console.log(AuthService.currentUser()); 
    }; 
    }]); 

在第一提交,我在控制檯中得到「未定義」,在第二次提交時,我在控制檯中看到預期的數據...我一直在閱讀關於返回一個承諾和什麼,只是有點不清楚精確實現給定的結構我的代碼...

+0

看看類似的問題http://stackoverflow.com/questions/17686307/factory-user-service-that-either-returns-a-諾言或緩存的數據/ 17686436#17686436 –

回答

1

看起來您正在嘗試在xhr請求完成之前登錄用戶。試試這個:

angular.module('myapp.services', []). 
factory('AuthService', ['$q', '$http', function($q, $http){ 
    var currentUser; 
    var isLoggedIn = false; 

    return { 
    login: function(user, pass) { 
     var deferred = $q.defer(); 
     $http({method: 'GET', url:'https://some-api/api/login/'+user+'/'+pass}). 
     success(function(data){ 
      currentUser = data; 
      isLoggedIn = true; 
      deferred.resolve(); 
     }); 
     return deferred.promise; 
    }, 
    isLoggedIn: function(){ return isLoggedIn; }, 
    currentUser: function(){ return currentUser; } 
    }; 
}]); 

然後

angular.module('myapp.controllers', []) 
.controller('LoginCtrl', ['$scope', 'AuthService', function(scope, AuthService) { 
    scope.update = function(user){ 
    AuthService.login(user.username, user.password).then(function() { 
     console.log(AuthService.currentUser()); 
    }); 

    }; 
}]); 
+0

我不得不將「返回延期」更改爲「返回deferred.promise」,然後它工作。謝謝! – bakedbean

+0

對不起。我更新了我的代碼以反映該編輯。 –