Ionic local storage and routing

670 views Asked by At

I am making an Ionic app and I am utilizing $http service to pull in articles from a server. My app has a list of articles with the option to go into a single 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 am using my controller to show this in the event that articles cannot be fetched:

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

    );
})

That works perfectly but I am having trouble fetching a single article from localStorage with my single controller:

.controller('GautengInnerCtrl', function ($scope, $stateParams, Articles) {
  $scope.articles = JSON.parse(window.localStorage.getItem("articles"));
  $scope.article = Articles.get($stateParams.articleId);
})
1

There are 1 answers

1
devqon On BEST ANSWER

You should check in your service if there are any articles in the localstorage, and retrieve 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;
        }
    }
});