Im using a REST Api that provides non-nested resources 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. The idea is first to get the description of an active element. Here i ask for an JSON, response looks like this :
{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.
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:
// 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){...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With