【问题标题】:How to inject user data in $resource call?如何在 $resource 调用中注入用户数据?
【发布时间】:2015-07-28 04:42:54
【问题描述】:

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

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

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

有可能吗?

【问题讨论】:

    标签: angularjs angularjs-resource


    【解决方案1】:

    这样的事情可能会奏效:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 2011-08-14
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多