Angular JS - 如何在完成函数后才能执行代码

时间:2014-12-17 12:45:11

标签: javascript angularjs asynchronous angularjs-directive angular-ui

我在AuthService.saveSession()

中有一个功能app.run

我在我的AuthService.isLoggedIn()函数中调用$stateChangeStart它说未定义,因为这两个函数同时被调用。

如何在$stateChangeStart完成后让我的代码执行AuthService.saveSession()

希望我能非常清楚地解释任何疑问,请发表评论。

更新

app.run(function($rootScope, $location, $state, $http, $q, AuthService){

AuthService.saveSession();

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState,fromParams){
alert(AuthService.isLoggedIn()); // It says undefined.

});

2 个答案:

答案 0 :(得分:1)

你可以使用$ q并返回一个承诺:

例如:

  function saveSession(){
      var deferred = $q.defer();
      //insert logic and async calls here
      //after everything is done, do this
      deferred.resolve(data); //where data is the data you want to get

      return deferred.promise;
  }

然后这样称呼:

  var promise = saveSession();
  promise.then(function(data){
      $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState,fromParams){
        alert(AuthService.isLoggedIn());
      });
  });

答案 1 :(得分:1)

在使用工厂时使用此方法

 //factory for AuthService service , put $q in dependency in factory

 saveSession:function(){
    var deferred = $q.defer();
    //insert logic and async calls here
    //after everything is done, do this
    deferred.resolve(data); //where data is the data you want to get

    return deferred.promise;
}
   AuthService.saveSession().then(function(status){
     //do action here after getting promise
     $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState,fromParams){

  //do what ever you want
  });
  })