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