Angular - extending $resource subobject with custom methods

前端 未结 4 579
不思量自难忘°
不思量自难忘° 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条回答
  •  猫巷女王i
    2020-12-02 08:25

    If you're using angular-resource 1.1.5 (which as far as I can tell actually works fine with angular 1.0.7), there is a transformResponse option you can specify when overriding $resource methods:

    angular.module('foo')
      .factory('Post', ['$resource', function($resource) {
    
        var Post = $resource('/api/posts/:id', { id: '@id' }, {
          query: {
            method: 'GET',
            isArray: true,
            transformResponse: function(data, header) {
              var wrapped = angular.fromJson(data);
              return wrapped.items;
            }
          }
        });
    
        Post.prototype.foo = function() { /* ... */ };
    
        return Post;
      }]);
    

    If you do this, you no longer have to manually pull the items out of the wrapped response, and each item will be an instance of Post that has access to the .foo method. You can just write:

    ..
    

    The downside to this is that you lose access to any of the outer fields in your response that aren't inside items. I'm still struggling to figure out a way to preserve that metadata.

提交回复
热议问题