【问题标题】:How can I determine when the differed execution will end so that I can load the data in AngularJs?如何确定不同的执行何时结束,以便我可以在 AngularJs 中加载数据?
【发布时间】:2018-03-30 17:56:57
【问题描述】:

我正在使用本地化 cookie 跟踪当前的文化。我想在应用程序启动时加载当前所选文化的所有消息并将它们与有关其文化的信息一起保存在localStorage 中,然后仅在所选文化更改时刷新它们(当@987654323 中'CurrentCulture' 的值时@ 与 cookie 中的不同)。

在我的控制器中,我设置 $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);
            }
        };

    });

getCachedMessagesForLanguagegetLocalisationsFromServer 完成之前返回undefined,所以在第一次加载时我没有任何消息。如果我刷新页面,那么我会正确获取它们。我该如何解决这个问题?

【问题讨论】:

    标签: angularjs localization local-storage deferred-execution


    【解决方案1】:

    getCachedMessagesForLanguage 返回一个 deferred.promise

    然后你可以做..

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

    【讨论】:

      猜你喜欢
      • 2014-01-09
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 2019-09-27
      • 2012-02-01
      • 2016-11-15
      • 2011-08-31
      相关资源
      最近更新 更多