Angular - extending $resource subobject with custom methods

前端 未结 4 577
不思量自难忘°
不思量自难忘° 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:09

    This is an old question, but I just ran into this issue myself. gargc's solution is the right approach, but there is an improvement. transformResponse accepts an array that gets passed to the $http service. Rather than completely replace the transform function, you can append your transform to the defaults to just make the updates you need:

    angular.module('foo')
        .factory('Post', function ($resource, $http) {
            var Post = $resource('/api/posts/:id', { id: '@id' }, {
                query: {
                    method: 'GET',
                    isArray: false,
                    transformResponse: $http.defaults.transformResponse.concat(function(data, header) {
                        angular.forEach(data.items, function(item, idx) {
                            data.items[idx] = new Post(item);
                        });
                        return data;
                    })
                }
            });
    
            Post.prototype.foo = function() { /* ... */ };
    
            return Post;
        });
    

提交回复
热议问题