离线存储和路由在Ionic中的应用

3

我正在制作一个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);
})

你确定在 $stateParams 中传递了正确的 id 吗? - Malek Hijazi
当有网络连接时,只需在第二个控制器中使用$scope.article = Articles.get($stateParams.articleId);即可正常工作。我只是不知道如何从本地存储中获取数据,在第二个控制器中。 - letterman549
1个回答

3
你应该在你的服务中检查本地存储中是否有文章,并在存在时检索它们。
.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;
        }
    }
});

非常感谢!运行得很顺利! - letterman549

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接