Search code examples
angularjspostngresource

POST a JSON array with ANGULARJS $resource


I need to do send a json array to a restful api from my angularjs application. I am using ngresources to do this. Since now, I have been abled to post and put single object with no problem, but now I need to send an array of objects and I can't.

I tried to do the call from a external rest application and it works fine but it's impossible from my angular application. I have trie to parse the objet with JSON.stringify but stills not working. I set the header 'Content-Type': 'application/json', as well on the $resources.

This is how I do the negresource:

.factory('AddSignosClinicos', function ($resource) {

    return $resource(dondeapuntar + "/Rest/Pacientedatossignosclinicos.svc/pACIENTEDATOSSIGNOSCLINICOSList/Add", {}, {
        create: { method: "POST", headers: { 'Content-Type': 'application/json', params: {} } }
    });
})

And this is how I call the function:

var objeto = JSON.stringify(SignosClinicosGuardar);

var signosClinicosService = new AddSignosClinicos(objeto);

signosClinicosService.$create().then(function () {});

I made a console.log of objeto, and is a proper json array.

Any idea?

Thank you very much

EDIT

I have tried $http component for the post request, and it worked! I don´t understand why is not working with ngResources, this is my code for $http:

  $http({
            url:    'http://localhost:1046/Rest/Pacientedatossignosclinicos.svc/pACIENTEDATOSSIGNOSCLINICOSList/Add',
            method: "POST",
            data: SignosClinicosGuardar,
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        });

Solution

  • To post an array of objects you'll need to add the option isArray: true to your $resource:

    .factory('AddSignosClinicos', function ($resource) {
        return $resource(
            "url-string-here", 
            {}, 
            {
                create: { 
                    method: "POST",
                    isArray: true
                }
            }
        );
    })
    

    Calling the new create function would look something like this:

    //some list of your object instances
    var array_of_objects = ...
    
    var saved_objects = AddSignosClinicos.create(
        array_of_objects
    );
    
    saved_objects.$promise.then(function() {
        ...
    });
    

    Note, the create vs $create, there's no $.

    See the Angular documentation on $resource