每当我离开页面然后重新进入时,Angular $ http就会触发

时间:2015-06-10 09:29:11

标签: ajax angularjs http caching

我有一个向服务器发出$ http请求的Ionic应用程序。我列出了一些文章,用户可以选择进入一篇文章。我的问题是,我注意到当我进入列出文章的页面时,它会调用检索文章列表。如果我离开那个页面然后又回来再次拨打电话。有没有办法缓存这些数据,以便只有在"拉到刷新"的实例中才会调用服务器。或设置一个计时器让它拨打电话?

我的服务:

.factory('Articles', function ($http) {
    var articles = [];
storageKey = "articles";

    function _getCache() {
        var cache = localStorage.getItem(storageKey );
        if (cache)
            articles = angular.fromJson(cache);
    }
    return {
        all: function () {
            return $http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function (response) {
                articles = response.data.items;
                console.log(response.data.items);
                return articles;
            });
        },
        get: function (articleId) {
            if (!articles.length) 
            _getCache();
            for (var i = 0; i < articles.length; i++) {
                if (articles[i].id === parseInt(articleId)) {
                    return articles[i];
                }
            }
            return null;
        }
    }
});

这是我的控制器:

.controller('ArticleCtrl', function ($scope, $stateParams, Articles) {
    $scope.articles = [];
    Articles.all().then(function(data){
        $scope.articles = data;
        window.localStorage.setItem("articles", JSON.stringify(data));
    }, 

    function(err) {
       if(window.localStorage.getItem("articles") !== undefined) {
          $scope.articles = JSON.parse(window.localStorage.getItem("articles"));
        }
    }

    );
})

1 个答案:

答案 0 :(得分:3)

您已经在缓存数据,因此只需将all更改为:

all: function () {
    var cache = localStorage.getItem(storageKey);
    // If cache, return a promise wich resolves with the cache
    if (cache) {
        var deferred = $q.defer();
        deferred.resolve(angular.fromJson(cache));
        return deferred.promise;
    } else {
        // if no cache, do a http call to get the data
        return $http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function (response) {
            articles = response.data.items;
            // store in cache
            localStorage.setItem(storageKey, articles);
            console.log(response.data.items);
        });
},