AngularJS - handling RESTful $resource response


I have an restful api and angularjs app. I am using $resource inside a factory to work with this api. I have a problem with one request. I POST my api to create some elements.


I need to pass in my request some data. Here is what I am doing:

$scope.someRequest = new SomeRequest(); // factory object returning an $resource
$scope.someRequest.some_field = 'abc';
$scope.someRequest.$save({someAdditionalParams:'123'}, function(values){...handling response...});

It works fine and POSTs data I want to post, but in this particular case my post response is array of objects.

[{somestuff:'123'}, {somestuff:'321'} ... ]

Angular tries to map it back to an object and throws me an error that object was expected but got an array. I tried to create a separate resource method with isArray:1, but it still failed with same kind of error.

So, my question is: how to handle this situation? Is it possible to cancel copying $save result to $resource object?

Problem courtesy of: Kirill Ustimov


Using $save, it will try to map it back. You can create a new action with isArray:true that will not try to map the result back. You would of course have to manually handle the results.

var someRequest = $resource('/api/service/thing/make-things',{'create':   {method:'POST', isArray:true}});
someRequest.create({some_field = 'abc',someAdditionalParams:'123'},function(data){
    $scope.someRequestArray = data;

True RESTful architecture is supposed to return what was created, that is why $save works the way it does. Your needs are slightly different so a custom action is needed.

Solution courtesy of: TheSharpieOne


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.