12

In angularjs resource, I would like to convert my json data into JS objects

//Complex object with inheritance chain
function Car(year, make){
    this.make = make;
    this.year = year;
}


var carResource = $resource("/api/car/id", {id: '@id'},
    {
        get: {
            method: 'GET',
            transformResponse: function(data, headersGetter){
                return new Car(data.make, data.year);
            }
        }
    }
)

However this does not seem to be happening

What I am getting back is a $resource object meaning that the properties make and year are set correctly, however the prototype of the returned object points to $resource

Is there a way where I can map my json data directly to my own objects?

Or will I have to write my own 'resource' implementation?

2
  • Take a look to decorator docs.angularjs.org/api/AUTO.$provide Commented Feb 2, 2014 at 20:14
  • Why do you use $resource if you want your own classes? Commented Feb 2, 2014 at 22:03

1 Answer 1

16

transformResponse is executed on $http level.

When you customise $resource actions with custom config object, that object is actually passed on to the underlying $http service. So if you specify a transformResponse callback, it will be executed on $http level, and the results of your transformation will be passed back on to $resource.

$resource service will instantiate new object from your response data (which is already transformed by the transformResponse callback) and this new object will be an instance of the $resource itself.

So, your car object will be an instance of the Car, but only for a moment, until it's properties are copied into a new $resource object.

Here's a simplistic view of the process:

  1. $resource service initiates request
  2. $http service sends request and receives the response
  3. $http service transforms the response (response is now instance of Car)
  4. $resource service receives the transformed response (from $http)
  5. $resource service makes an instance of itself using transformed response properties (result is now instance of $resource)

Anyway, I don't recommend decorating or extending the $resource service, because it's simpler to write your own implementation using $http service.

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

2 Comments

Thanks, I misunderstood the purpose of the transformResponse method and actually thought I could change what the $resource returns. A simple wrapper around $http service would be good enough for me.
Maybe to use resource interceptor github.com/angular/angular.js/issues/11409

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.