我正在制作一个 Ionic 应用程序,并且正在利用 $http 服务从服务器提取文章。我的应用程序有一个文章列表,可以选择进入一篇文章。我的工厂是这样的:
.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;
}
}
});
我正在使用我的 Controller 在无法获取文章的情况下显示此内容:
.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"));
}
}
);
})
效果很好,但我在使用单个 Controller 从 localStorage 获取一篇文章时遇到了问题:
.controller('GautengInnerCtrl', function ($scope, $stateParams, Articles) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
$scope.article = Articles.get($stateParams.articleId);
})
最佳答案
您应该检查您的服务本地存储中是否有任何文章,如果有则检索它们:
.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;
}
}
});
关于angularjs - Ionic 本地存储和路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750436/