1

I've got a simple dataFactory that retrieves some posts:

dataFactory.getPosts = function () {
    if (this.httpPostsData == null) {
        this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer[orderby]=date")
            .success(function (posts) {

            })
            .error(function (posts) {
                console.log('Unable to load post data: ' + JSON.stringify(posts));
            });
    }

    return (this.httpPostsData);
}

The controller calls the factory and I understand that the posts are promises -so there is some stuff done on success and some stuff that is done anyway. This works fine.

.controller('CardsCtrl', function($scope, dataFactory,
        $ionicSlideBoxDelegate, $stateParams) {

    var parentID = $stateParams.parentID;
    var keyIDNumber = $stateParams.keyID;

    $scope.card = [];

    var httpcall = dataFactory.getPosts()
        .success(function (posts) {
            $scope.card = dataFactory.getChildPosts(parentID, posts, keyIDNumber);

            $ionicSlideBoxDelegate.update();
        });

    // do other stuff ......
});

However, I'm now trying to cache the post data - but when the controller is called a second time it returns the error .success is not a function. I assume the is because the posts have already been returned - but how do I handle this?

kiswa
  • 14,737
  • 1
  • 21
  • 29
bigfatfrog
  • 59
  • 9

2 Answers2

1

That's because you're not returning the $http.get, you're returning the promise after .success and .error have already been handled.

You can either change the controller to call .then on the return, or change the service to just return the $http.get (remove the .success and .error) and handle them in the controller.

If you change the controller to use .then you'll also need to update the .success function in the service to return posts;.

kiswa
  • 14,737
  • 1
  • 21
  • 29
0

Have you tried setting the cache option to true in your $http call? Like here https://stackoverflow.com/a/14117744/1283740

Maybe something like this...

angular.module('foo', [])

.factory('dataFactory', ['$http', function($http){

  var dataFactory = {
          getPosts: getPosts
      };

  function getPosts(){

    var url = "http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer[orderby]=date"

    return $http({ cache: true, url: url, method: 'GET'})
      .error(function (posts) {
        console.log('Unable to load post data: ' + JSON.stringify(posts));
      });

  };

   return dataFactory;

}])
Community
  • 1
  • 1
Matt Herbstritt
  • 4,754
  • 4
  • 25
  • 31