0

I have the following AngularJS factory where I consume my API data:

.factory('posts', function posts($http) {

    var posts = [];
    $http.get('/api').success(function(data) {
        posts = data;
    });

    /* === return this after $http is done === */

    return {
        get: function(offset, limit) {
            return posts.slice(offset, offset + limit);
        },

        total: function() {
            return posts.length;
        }
    }

});

My problem is that I need to return the get() just after the posts array is populated, when the $http request is done.

Can someone explain me how to achive this? Return the factory methods just when the $http.get() is done.

1 Answer 1

2

you must return the promsie.

.factory('posts', function posts($http,$q) {

var posts = [];


/* === return this after $http is done === */

return {
    get: function(offset, limit) {
        var deferred = $q.defer();
        if(posts.length==0){
           $http.get('/api').success(function(data) {
               posts = data;
               deferred.resolve(posts.slice(offset, offset + limit));
           });
         } else {
            deferred.resolve(posts.slice(offset, offset + limit));
         }
         return deferred.promise;            
    },
    total: function() {
        return posts.length;
    }
  }

});
Sign up to request clarification or add additional context in comments.

4 Comments

Its not returning anything
in you controller user then function to get data, posts.get(offset,limit).then(function(data){here is the data})l
But each time when Im calling I get the same results, the thing is that I need to populate the posts = [ // all posts ] and on get just send some parts of the array, how can I achive this?
i updat e my answer that the http call onli o the first time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.