简体   繁体   English

链接ngResource承诺

[英]Chaining ngResource promises

Im using a REST Api that provides non-nested resources API. 我使用REST Api提供非嵌套资源API。 That leads to chained calls, that i want to make with promises. 这导致了链接的电话,我想用承诺做。 Im using the ngResource from angular, and im having problem chaining the calls. 我使用角度的ngResource,我有问题链接调用。 The idea is first to get the description of an active element. 这个想法首先得到一个活跃元素的描述。 Here i ask for an JSON, response looks like this : 在这里我要求一个JSON,响应如下:

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

After i got this information, i try to get the data about blocks. 获得此信息后,我尝试获取有关块的数据。 The implementation looks like this: 实现如下:

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...
                .......

            });
        })

The problem that the second then gets undefined block, although the GET call get a correct JSON from the server. 第二个然后获得未定义块的问题,尽管GET调用从服务器获得正确的JSON。

Im wondering if i am using the chaining of the promises incorrectly or im using the elements wrong 我想知道我是否正在使用错误的链接或我使用错误的元素

You are not correctly chaining your promises. 你没有正确地链接你的承诺。 For each block you sending another request to the server immediatly. 对于每个块,您立即向服务器发送另一个请求。

Use $q.all for chaining: 使用$ 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;
    }));

This should give you the array of resulting blocks here: }).then(function(blocks){... 这应该在这里为你提供结果块的数组: }).then(function(blocks){...

The chained promises use the previous promise's result as an input. 链式承诺使用先前承诺的结果作为输入。 You have no return in your first promise, thus the second receiving undefined as its block. 你的第一个承诺没有回报,因此第二个接收未定义为其块。

You should return element or whatever is relevant in your first promise. 你应该在你的第一个承诺中返回元素或任何相关内容。

This is described in the $q documentation . 这在$ q文档中有描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM