如何在localStorage中存储从$资源中检索的值?

时间:2015-01-03 20:26:34

标签: javascript angularjs asynchronous local-storage

我的服务使用googleapis解析RSS并返回包含其他对象的数组对象。 下面是chrome控制台输出:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
   0: Object
   1: Object
   2: Object
   3: Object

但是在我的控制器中无法使用localStorage来检索数据,控制台输出只返回括号或什么都没有:

$scope.feeds = FeedList.get();
window.localStorage.setItem('savedData', JSON.stringify($scope.feeds));

console.log('TEST : ' + window.localStorage['savedData']);
console.log('TEST : ' + JSON.parse(window.localStorage.getItem('savedData')));
console.log('TEST : ' + JSON.parse(window.localStorage['savedData']));

输出:

TEST : []
TEST : 
TEST : 

拜托,出了什么问题?

service.js

.factory('FeedLoader', function ($resource) {
        return $resource('http://ajax.googleapis.com/ajax/services/feed/load', {}, {
            fetch: { method: 'JSONP', params: {v: '1.0', callback: 'JSON_CALLBACK'} }
        });
    })

.service('FeedList', function ($rootScope, FeedLoader) {
    var feeds = [];
    this.get = function() {
        var feedSources = [
            {title: 'rss1', url: 'http://www.website.com/rss/feed/rss_feed_25300'},
            {title: 'rss2', url: 'http://www.website.com/rss/feed/rss_feed_10720'},
        ];
        if (feeds.length === 0) {
            for (var i=0; i<feedSources.length; i++) {
                FeedLoader.fetch({q: feedSources[i].url, num: 10}, {}, function (data) {
                    var feed = data.responseData.feed;
                    console.log(feed.entries);
                    feeds.push(feed.entries);
                });
            }
        }
        return feeds;
    };
})

2 个答案:

答案 0 :(得分:2)

FeedList.get()使用异步并且$scope.feeds不会立即填充,这有什么不对。

试试这个:

$scope.feeds = FeedList.get();
$scope.feeds.then(function () {
    // $scope.feeds is done loading now
    window.localStorage.setItem('savedData', JSON.stringify($scope.feeds));

    console.log('TEST : ' + window.localStorage['savedData']);
    console.log('TEST : ' + JSON.parse(window.localStorage.getItem('savedData')));
    console.log('TEST : ' + JSON.parse(window.localStorage['savedData']));
});

修改:既然您已经为自己的服务提供了代码,那么很明显它并没有返回承诺。您需要这样做,以便服务的消费者能够等待结果:

.service('FeedList', function ($rootScope, $q, FeedLoader) {
    var feeds;
    this.get = function() {
        var feedSources = [
            {title: 'rss1', url: 'http://www.website.com/rss/feed/rss_feed_25300'},
            {title: 'rss2', url: 'http://www.website.com/rss/feed/rss_feed_10720'},
        ];

        if (!feeds) {
            var feedPromises = feedSources.map(function (source) {
                return FeedLoader.fetch({q: source.url, num: 10}, {}).$promise
                .then(function (data) {
                    return data.responseData.feed.entries;
                });
            });

            feeds = $q.all(feedPromises)
            .then(function (retrievedFeeds) {
               return Array.prototype.concat([], retrievedFeeds);                
            });
        }
        return feeds;
    };
})

答案 1 :(得分:0)

问题是你没有正确处理异步请求,所以:

$scope.feeds = [];

console.log('TEST : Load feeds async');

FeedList.get().then(function () { // each feed comes as argument
    angular.forEach(arguments, function (feed) {
        $scope.feeds.concat(feed); // merge arrays
    });

    window.localStorage.setItem('savedData', JSON.stringify($scope.feeds));

    console.log('TEST : ' + window.localStorage['savedData']);
    console.log('TEST : ' + JSON.parse(window.localStorage.getItem('savedData')));
    console.log('TEST : ' + JSON.parse(window.localStorage['savedData']));
});

服务:

.service('FeedList', function ($q, $rootScope, FeedLoader) {
    this.get = function () {
        var promises = []; // to handle async loading 

        var feedSources = [{
            title: 'rss1',
            url: 'http://www.website.com/rss/feed/rss_feed_25300'
        }, {
            title: 'rss2',
            url: 'http://www.website.com/rss/feed/rss_feed_10720'
        }];

        angular.forEach(feedSources, function (source) {
            var defer = $q.defer();

            FeedLoader.fetch({
                q: source.url,
                num: 10
            }, {}, function (data) {
                var feed = data.responseData.feed;
                defer.resolve(feed.entries); // todo - need to handle errors with 'defer.reject'
            });

            promises.push(defer.promise);
        });

        return $q.all(promises);
    };
})