0

I have thin service wrapped around $resource to handle communication with API. Usually it works just as needed. However now I would like to extend get from $resource.

Let's say that front end need returned data in certain order. Back end for whatever reason can not be modified. Sort order will be needed application wide, so changing it in $resource definition would be best.

Official documentation is silent on this topic. Adding new functions is well documented, but changing default ones is not. How to (ideally) add .then() to get.

4
  • 1
    Have you tried use $provide.decorator ? Anyway you wrap your method and attach $q there for example: function wrap() { var def = $q.defer; dosmthAsync(def.resolve); return def} Commented Nov 5, 2015 at 8:41
  • I have full controll over definition of my service and $resource used to communicate with API, though idea of wrapping function got me interested. Could I wrap get returned by $resource that way? Can You post that as answer? Commented Nov 5, 2015 at 8:51
  • yes. let me do that. Commented Nov 5, 2015 at 8:53
  • guys've answered already. You can try return $q.defer from transformResponse. But as i remember it returns promise. Commented Nov 5, 2015 at 8:57

2 Answers 2

2

I'm not sure how your thin service wrapper looks like, but if you want to do something with your response you could use transformResponse-property.

angular.module('app', ['ngResource'])
   .factory('myWrapper', function($resource){
      return function(url){
         return $resource(url,
                          {},
                          {
                           get: {method: 'GET',
                                 transformResponse: function(data, headers){
                                   data.sort() //or something
                                   return data;
                                 }
                                }
                           }
                        );
                    };

      });

this will override default get.

Sign up to request clarification or add additional context in comments.

4 Comments

original $resource get definition comes down to {method: 'GET'} ? Silly me :D I was worried that its something more complex.
hehe yes, not very complex definition
notice: data will be a string. you need to parse it yourself depending on the format (JSON / XML) you expect.
and headers is a function that returns the headers
1

The transformResponse option might be handy if you want to modify/sort the response.

1 Comment

Can You give me code snippet for adding "transformResponse" to get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.