Angular - 使用自定义方法扩展 $resource 子对象 [英] Angular - extending $resource subobject with custom methods

查看:28
本文介绍了Angular - 使用自定义方法扩展 $resource 子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,.query() 方法的结果是一个数组,可以使用以下(工厂)代码轻松扩展一些方法(业务逻辑):

In most cases the result of <custom-resource>.query() method is an array, which can be easily extended with some methods (business logics) with the following (factory) code:

var Data = $resource('http://..');
Data.prototype.foo = function() {return ...};

这非常适合与 ng-repeat/ng-class 一起使用,如下所示:

this is perfect for using with ng-repeat / ng-class, like so:

<tr ng-repeat="item in responseData" ng-class="{warning: item.foo()}">..</tr>

我的问题是每个列表响应都封装在一个对象中,除了实际列表之外,还有一些元属性(排序信息等),所以返回的最终对象是这样的:

My problem is that every list response is encapsulated in an object which, besides the actual list, has some meta-properties (sorting info etc), so the final object returned is like this:

{ order_field: "name", items: [{..}, {..},{..}] }

现在,我如何使用 ng-repeat/ng-class 制作与以前相同的东西?

Now, how do I make the same thing as previously with ng-repeat/ng-class?

<tr ng-repeat="item in responseData.items" ng-class="????">..</tr>

前面的方法不起作用,因为foo"方法是在 responseData 上定义的,而不是在 item 对象上定义的

the previous method won't work as the "foo" method is defined on responseData and NOT on item object

有没有办法直接扩展用于实例化列表中对象的基类?

Is there any way to directly extend the base class used for instantiating objects on the list?

谢谢!

推荐答案

我以前发现过这个问题,解决方案似乎是 transformResponse,正如 John Ledbetter 在另一个答案中所说.

I've found that problem before, and the solution seems to be transformResponse, as John Ledbetter says in the other answer.

无论如何,如果您需要保留整个对象,并且还需要在items"中的数组中填充资源实例,您可以使用以下技巧来实现:

Anyway, if you need to keep the entire object, and also having the array in 'items' filled with instances of the resource, you might be able to do it with the following trick:

以约翰的回答为例,稍作修改:

Taking the example from John's answer, and modifying it a bit:

angular.module('foo')

  .factory('Post', ['$resource', function($resource) {

    var Post = $resource('/api/posts/:id', { id: '@id' }, {
      query: {
        method: 'GET',
        isArray: false, // <- not returning an array
        transformResponse: function(data, header) {
          var wrapped = angular.fromJson(data);
          angular.forEach(wrapped.items, function(item, idx) {
             wrapped.items[idx] = new Post(item); //<-- replace each item with an instance of the resource object
          });
          return wrapped;
        }
      }
    });

    Post.prototype.foo = function() { /* ... */ };

    return Post;
  }]);

这篇关于Angular - 使用自定义方法扩展 $resource 子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆