POST a JSON array with ANGULARJS $resource
Asked Answered
H

1

6

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'
            }
        });
Heterosexual answered 29/2, 2016 at 15:52 Comment(3)
provide piece of code and dig deep on the json stringify error please.Ossy
Oh, sorry for that. I have added the code above. Thank youHeterosexual
Try adding the option isArray: true to your returned $resource. See ng docs on $resourceRaina
R
6

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

Raina answered 29/2, 2016 at 17:14 Comment(2)
I've added some pseudo-code showing the basic usage, since I'm not sure you are calling into the resource method correctly.Raina
You are right. I was calling the $resource wrong. Thank you a lot! :)Heterosexual

© 2022 - 2024 — McMap. All rights reserved.