0

How can I return the root from this API call in this factory? Now its undefined. I understand that this is because the ajax call is async but how to wait for it?

app.factory('ApiFactory', ['$resource', function($resource) {
    return $resource( 'http://localhost:8080/rest/forum/categories/:categoryId', { bookId: '@categoryId' }, { });
}]);


app.factory('ApiParser', ['ApiFactory', function(ApiFactory) {

    function createSubjectArray(children){
        var subjets = [],
            node,
            subject, i;
        for(i = 0; i < children.length ; i++){
            node = children[i];
            subject = {};
            subject.text = node.value.nameKey;

            if(!node.leaf){
                subject.items = createSubjectArray(node.children);
            } else {
                subject.spriteCssClass = "subject";
            }
            subjets.push(subject);
        }       
        return subjets; 
    }


    return {
        get: function() {
            var root
            var data = ApiFactory.get({categoryId : 1},function(data) {
                root = { text: data.value.nameKey, expanded: true, items: createSubjectArray(data.children)};

            });

            return root;
        }
    }
}]);
pethel
  • 5,397
  • 12
  • 55
  • 86
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Stewie Nov 29 '13 at 09:56

1 Answers1

0

You can use $q service:

app.factory('ApiParser', ['ApiFactory','$q', function(ApiFactory, $q) {

...

return {
    get: function() {
        var defer = $q.defer();
        var root;
        var data = ApiFactory.get({categoryId : 1},function(data) {
            root = { text: data.value.nameKey, expanded: true, items: createSubjectArray(data.children)};

            defer.resolve(root);

        }, function(data, status) { defer.reject(status); });

        return defer.promise;
    }
}
}]);

And usage:

ApiParser.get().then(function(data){ $scope.root = data; }, function(status) { // error logic });
MRB
  • 3,752
  • 4
  • 30
  • 44