链接 ngResource 承诺

Chaining ngResource promises

我正在使用提供非嵌套资源 API 的 REST Api。这导致链式调用,我想做出承诺。我正在使用来自 angular 的 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,但第二个获得未定义块的问题。

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

链式承诺使用前一个承诺的结果作为输入。您的第一个承诺中没有 return,因此第二个承诺未定义。

您应该 return 元素或任何与您的第一个承诺相关的内容。

这在 the $q documentation 中有描述。

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

使用 $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){...