簡體   English   中英

Angular JS-如何僅在完成函數后才執行代碼

[英]Angular JS - How can i execute code only after completion of a function

我在app.run有一個函數AuthService.saveSession()

我在$stateChangeStart函數中調用AuthService.isLoggedIn()時說未定義,因為兩個函數同時被調用。

AuthService.saveSession()完成后,如何使我的代碼執行$stateChangeStart

希望我能很清楚地解釋任何疑問,請發表評論。

更新資料

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.

});

您可以使用$ q並返回一個promise:

例如:

  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());
      });
  });

在使用工廠時使用此方法

 //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
  });
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM