Angular - extending $resource subobject with custom methods

前端 未结 4 575
不思量自难忘°
不思量自难忘° 2020-12-02 07:42

In most cases the result of .query() method is an array, which can be easily extended with some methods (business logics) with the follow

4条回答
  •  情歌与酒
    2020-12-02 08:24

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

提交回复
热议问题