如何在$resource调用中注入用户数据



我使用$resource从后端服务器获取json数据。

首先,我得到一个id列表,其中包含第一个资源调用。然后,对于接收到的每个id,我使用$resource来获取与该id相关的数据。

现在,问题是:我想将响应与发送的id关联起来,这样我就可以将数据记录到哈希表中。(如:$ scope.table[响应。Id] = data;. 我发现的唯一方法是让API在json响应中发回id,但我想将id与查询关联,这样我就知道哪个id是我得到的响应,而无需API将其发回。

下面是我当前的代码(简化了,只是为了了解大意):

// the factory. eg I send /rest/item/12345
app.factory('Item', function ($resource) {
    return $resource("/rest/item/:id", { id: '@id'})
});
// the call (in a loop)
// I need to get { "id" : 12345, "text" : "blahblahblah" } 
Item.get({ id : itemId },
  function(data){
    $scope.table[data.id] = data;
  });

我想这样写:

// the call (in a loop). 
// I would like to only need to get { "text" : "blahblahblah" } 
Item.get({ id : itemId },
  function(id, data){
    $scope.table[id] = data;
  });

我想我可以用这个形式:

$scope.table[itemId] = Item.get({id : itemId});

但是我需要$scope。表[itemId]一直是一个"正确"的值,而不是一个承诺,我希望它在我收到答案时被更新。

这样做可能会起作用:

// get the array of ids
ItemIds.get({},
  function(ids){
    // for each id, make the request for the actual item
    ids.forEach(function(id) {
        Item.get({ id : id },
          function(data){
          // in this nested callback, you have access to data and id
          $scope.table[id] = data;
        });
    });
  });

最新更新