Ionic local storage and routing
I am making an Ionic app and I am using the $ http service to post articles from the server. My app has a list of articles with the option to jump into one article. My factory looks like this:
.factory('Articles', function ($http) {
var articles = [];
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) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
});
I use my controller to show this in case articles cannot be retrieved:
.controller('ThisCtrl', 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"));
}
}
);
})
This works great, but I'm having trouble getting one article from localStorage using my only controller:
.controller('GautengInnerCtrl', function ($scope, $stateParams, Articles) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
$scope.article = Articles.get($stateParams.articleId);
})
+3
source to share
1 answer
You should check your service if there are any articles in localstorage and get them if they are:
.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);
localStorage.setItem(storageKey, 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;
}
}
});
+3
source to share