我正在创建一个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('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"));
}
}
);
})
完美无缺,但我无法使用我的单一控制器从localStorage中获取一篇文章:
.controller('GautengInnerCtrl', function ($scope, $stateParams, Articles) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
$scope.article = Articles.get($stateParams.articleId);
})
答案 0 :(得分:3)
如果localstorage中有任何文章,您应该检查您的服务,并检查它们是否为:
.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;
}
}
});