使用$ resource从服务器解析数据

时间:2013-11-29 08:58:51

标签: angularjs

如何在此工厂中从此API调用返回根?现在它未定义。我明白这是因为ajax调用是异步但是如何等待呢?

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;
        }
    }
}]);

1 个答案:

答案 0 :(得分:0)

您可以使用$ q服务:

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;
    }
}
}]);

用法:

ApiParser.get().then(function(data){ $scope.root = data; }, function(status) { // error logic });