链接ngResource承诺

时间:2015-10-19 09:32:01

标签: javascript json angularjs ngresource

我正在使用提供非嵌套资源API的REST Api。这导致了链接的电话,我想用承诺做。我使用角度的ngResource,我有问题链接调用。这个想法首先得到一个活跃元素的描述。在这里我要求一个JSON,响应如下:

{id : 0, block : [0,3,4]} 

获得此信息后,我尝试获取有关块的数据。实现如下:

Element.get({'id':state.elementID}).$promise.then( function(element) {
            // Element hast block entry with array of belonging blockIDs
            angular.forEach(element.block, function(blockId){
                // Get all the Blocks, that have the defined ID ( Foreign key)
                return Block.get({'id':blockId}).$promise;
            });
        }).then(function(block){
            // Create an element and ADD it to the model
            var uiElem = new UIElem(block.id, "#",block.name, "block");
            $scope.list.push(uiElem);
            angular.forEach(block.parameter, function(element){
                /// Chain other calls...
                .......

            });
        })

第二个然后获得未定义块的问题,尽管GET调用从服务器获得正确的JSON。

我想知道我是否使用了错误的链接或使用错误的元素

2 个答案:

答案 0 :(得分:1)

你没有正确地链接你的承诺。对于每个块,您立即向服务器发送另一个请求。

使用$ q.all进行链接:

    // Element hast block entry with array of belonging blockIDs
    return $q.all(element.block.map(function(blockId){
        // Get all the Blocks, that have the defined ID ( Foreign key)
        return Block.get({'id':blockId}).$promise;
    }));

这应该为您提供结果块数组: }).then(function(blocks){...

答案 1 :(得分:0)

链式承诺使用先前承诺的结果作为输入。你的第一个承诺没有回报,因此第二个接收未定义为其阻止。

你应该在你的第一个承诺中返回元素或任何相关内容。

the $q documentation中描述了这一点。

相关问题