如何确定不同的执行何时结束,以便我可以在AngularJs中加载数据?

问题描述:

我使用本地化cookie来跟踪当前的文化。我想在应用程序启动时加载当前所选文化的所有消息,并将它们连同关于他们的文化的信息一起保存在localStorage中,然后仅当所选文化发生更改(在localStorage中的值不同于在cookie中)。如何确定不同的执行何时结束,以便我可以在AngularJs中加载数据?

在我的控制,我设置 $scope.messages = localisationService.messages(localisationMessagesUrl, currentCulture);

localisationService,我有

app.service("localisationService", function ($q, $http, localStorageService) { 

     var getCachedMessagesForLanguage = function (localisationMessagesUrl, language) { 
      console.log('getCachedMessagesForLanguage'); 
      var messages = localStorageService.get('Localisation'); 
      if (!messages || language !== localStorageService.get('Language')) { 

       getLocalisationsFromServer(localisationMessagesUrl).then(function (serverMessages) { 
        localStorageService.add('Localisation', messages); 
        localStorageService.add('Language', language); 

       }); 
      } 
      return localStorageService.get('Localisation') 

     } 

     function getLocalisationsFromServer(localisationMessagesUrl) {    
      return $q(function (resolve) { 
       $http.get(localisationMessagesUrl) 
        .then(function (response) { 
         resolve(response.data); 
        }); 
      }); 
     }   

     return {     
      messages: function (localisationMessagesUrl, language) { 
       return getCachedMessagesForLanguage(localisationMessagesUrl, language); 
      } 
     }; 

    }); 

getCachedMessagesForLanguage回报undefinedgetLocalisationsFromServer结束,所以在第一次加载我没有消息。如果我刷新页面,然后我正确地得到它们。我该如何解决这个问题?

化妆getCachedMessagesForLanguage返回deferred.promise

然后,您可以做..

getCachedMessagesForLanguage(localisationMessagesUrl, 
language).then(function(Localisation) { 
    return getLocalisationsFromServer(localisationMessagesUrl) 
}).then(function(responseFromGetLocalisationsFromServer) { 
    // do your thing here 
})