Angular $ http fires every time I exit a page and then back

I have an Ionic application that makes an HTTP request to a server. I list a number of articles, and the user has the opportunity to go to one article. My problem is that I noticed that when I visited the page listing the articles, it made a call to get a list of articles. If I exit this page, I will make you call again. Is there a way to cache this data so that it only makes a call to the server if there is a "pull to refresh" instance or set a timer to make calls?

My service:

.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;
        }
    }
});

and here is my controller:

.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"));
        }
    }

    );
})
+4
source share
1 answer

, 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);
        });
},
+3

All Articles