ptr
ptr

Reputation: 3384

Restangular put requests.. how and why?

If I have a resource, e.g.

var resource = Restangular.all('things');

and I have json object that I want to post to the API

jsonObj = {
  someVar: "x",
  anotherVar: "y"
}

I can simply do

resource.post(jsonObj).then( ...etc... )

Now if I update the model on the clientside and want to save the changes, why can I not do:

resource.put(thingId, updatedJsonObj)

I'm having trouble getting my head around the demos around on the internet, as they all appear to need to do a get request before they can do a put? Which seems odd. It's worth mentioning that I am using Restangular in a SERVICE, not in a controller or directive. My service has a variable allMyThings which is the result of resource.getList() and I use that in various places in the application

Upvotes: 2

Views: 831

Answers (1)

meriadec
meriadec

Reputation: 2983

Actually, if you take one item in the collection returned by getList(), you can use .save() on it, and it will call PUT method.

angular.module('demo').controller('DemoCtrl', function (myList) {

  // myList is populated by Restangular.all('...').getList();

  var item = myList[0];

  item.name = 'foo';

  item.save()                // this one did a PUT :)
    .then(function (res) {
       // ...
    });

});

See it in the docs.

NOTE :

Restangular will use the id property as id for PUT, DELETE, etc. calls. If you want to change that behaviour, use this in module config :

RestangularProvider.setRestangularFields({
  id: "_id"
});

Upvotes: 1

Related Questions