AngularJS工厂函数无法访问本地存储的缓存变量

时间:2015-01-09 05:30:47

标签: javascript ajax angularjs

此时我已经在这里待了10多个小时。这对我来说没有意义。我迫切需要澄清我做错了什么。下面是一个简单的工厂函数,它为JSON文件进行AJAX调用。没有异步。数据问题和一切正常。我遇到的问题是我正在尝试保存返回的结果并在以后访问它。如果填充了变量,那么我不必再进行第二次AJAX调用,我可以简单地获取局部变量的内容。我意识到还有其他方法可以做到这一点,但我特别喜欢使用这种工厂方法。

storyDataAsFactory.$inject = ['$log', '$http', '$q'];

angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);

function storyDataAsFactory($log, $http, $q) {
    var storiesCache = [];

    function getStories(url) {
        url = url || '';

        if (url !== '') {
            var deferred = $q.defer();

            alert('inside getStories, length of storiesCache = ' + storiesCache.length); // this is always zero! Why?

            //determine if ajax call has already occurred;
            //if so, data exists in cache as local var
            if (storiesCache.length !== 0) {
                $log.info('Returning stories from cache.');

                deferred.resolve(storiesCache);
                return deferred.promise;
            }

            $http({method:'GET', url:url})
                .success(function (data, status, headers, config) {
                    deferred.resolve(data);
                })
                .error(function (data, status, headers, config) {
                    deferred.reject(status);
                });

            return deferred.promise;
        } else {
            $log.error('(within storyDataAsFactory) Failed to retrieve stories: URL was undefined.');
        }
    }

    return {
        stories: storiesCache,

        getStories: function(url) {
            alert('inside return factory object, length of stories = ' + this.stories.length);
            //getStories returns a promise so that routeProvider
            //will instantiate the controller when resolved
            return getStories(url);
        }
    };
}

1 个答案:

答案 0 :(得分:0)

您需要使用承诺。我没有运行下面的代码,但这是个主意:

angular.module('ccsApp').service('storyDataAsFactory', storyDataAsService);

function storyDataAsService($log, $http, $q) {
    var storiesCache = [];

    function getStories(url) {

        url = url || '';

        if (url !== '') {
            alert('inside getStories, length of storiesCache = ' + storiesCache.length); // this is always zero! Why?
            if (storiesCache.length == 0) {
               return $http({method:'GET', url:url});
            } else {
                var deferred = $q.defer();
                deferred.resolve(storiesCache);
                return deferred.promise;
            }
        } else {
            $log.error('(within storyDataAsFactory) Failed to retrieve stories: URL was undefined.');
        }
    }

    return {
        getStories: function(url) {
            return getStories(url).then(function(stories) {
                // Do whatever
                return stories;
            });
        }
    };
}


storyDataAsService.getStories().then(function(stories) {
    $scope.stories = stories
})