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

问题描述

在大多数情况下的结果<定制的资源和GT; .query()方法是一个数组,可以用一些方法(业务逻辑)与轻松扩展下面的(工厂)code:

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-重复/ NG级使用,像这样:

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: [{..}, {..},{..}] }

现在,我怎么做同样的事情,pviously $ P $与NG-重复/ NG级?

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>

在previous方法不会为foo的工作方法上定义 responseData ,而不是项目对象

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

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

谢谢!

推荐答案

我以前就发现问题,解决方案似乎是 transformResponse ,约翰·莱德贝特说在对方的回答。

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

总之,如果你需要保持整个对象,并且还具有在充满资源的情况下,'项目'的数组,你也许可以用下面的把戏做到这一点:

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

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

07-29 14:19
查看更多