2015-10-19 159 views
3

我使用REST Api提供非嵌套資源API。這導致連鎖的電話,我想與承諾。我從角度使用ngResource,並有問題鏈接調用。這個想法首先得到一個活動元素的描述。在這裏,我要求一個JSON,響應如下所示:鏈接ngResource承諾

{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。

我想知道如果我使用的承諾的鏈接或不正確使用鏈式承諾使用先前承諾的結果作爲輸入的元素錯

回答

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

+0

謝謝,這是一個很好的答案。我仍然有一個問題:由於在下面的調用鏈中,例如,塊需要。我如何將這些傳遞給其他「當時」功能?擴展原型對我來說是一個虛假的,有沒有更好的解決方案? – Sonne

+0

當你在下面的'then'中獲得一個數組(塊)時,你應該能夠訪問例如blocks [0] .id。 如果幫助其他可能有相同問題的人是正確的,請接受我的回答。 –

+0

Firefox抱怨說element.block是未定義的。爲什麼? – Sonne

0

IM。你的第一個承諾沒有回報,因此第二個接收未定義爲其塊。

您應該返回元素或任何與您的第一個承諾相關的內容。

這在the $q documentation中描述。