代码之家  ›  专栏  ›  技术社区  ›  Dennis Hackethal

操纵从$resource返回的集合

  •  1
  • Dennis Hackethal  · 技术社区  · 10 年前

    我有一个服务叫 Message 它从API返回消息。它看起来很简单:

    app.factory('Message', function($resource) {
      return $resource('http://localhost:3000/messages/:id');
    });
    

    它工作正常,我在控制器中使用它将消息分配给我的作用域:

    app.controller('MessagesCtrl', function($scope, Message) {
      $scope.messages = Message.query();
    }
    

    当我登录时 $scope.messages 在浏览器的控制台中,它看起来如下所示:

    [$promise: Promise, $resolved: false]
      0: Resource
      1: Resource
      2: Resource
      3: Resource
      $promise: Promise
      $resolved: true
      length: 4
      __proto__: Array[0]
    

    到目前为止,很好-四条消息。我希望能够专门处理此集合中的元素,例如删除、更新和添加元素。

    基于 this answer ,这是我试图删除具有特定id的邮件的原因:

    $scope.messages = $scope.messages.filter(function(obj) {
      return (object.id != 6);
    });
    

    但这一转变 $scope.messages 转换为空集合。如何按id从资源集合中删除特定元素?此外,如何用另一个对象替换此集合中的现有元素?

    1 回复  |  直到 7 年前
        1
  •  2
  •   PSL    10 年前

    $resource执行promise的自动扩展(作为一种方便的方法),并将响应附加到返回的对象本身,但在直接操作数据时,尤其是在解析之前尝试访问数据时,就不会这么做了。因此,如果您想操纵数据,则需要等待承诺得到解决。

    i、 电子:-

       //chain through the promise.
       Message.query().$promise.then(function(messages){
          $scope.messages = messages.filter(function(obj) {
           return (obj.id != 6);
          });
       });
    

    或者您也可以(使用现有代码):

      $scope.messages.$promise.then(function(messages){
         //Since you are overwriting the object here, there will no longer be a $Promise property so be careful about it when you try to chain through elsewhere after this
         $scope.messages = messages.filter(function(obj) {
           return (obj.id != 6);
          });
      });