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

How to inject user data in $resource call?

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

首先,我通过第一个资源调用获得了一个 ID 列表。然后,对于收到的每个 ID,我使用 $resource 来获取与此 ID 关联的数据。

现在,问题是:我想将响应与发送的 ID 相关联,这样我就可以将数据记录到哈希表中。 (例如:$scope.table[response.id] = 数据;)。我发现的唯一方法是让 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.table[itemId] 始终是一个 "correct" 值,而不是一个承诺,我希望它在我收到答案时立即更新。

可能吗?

类似这样的方法可能有效:

// 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;
        });
    });
  });