问题
I'm using a regularized element and trying to save it. If it's a new element it's calling post in exactly the format I want.
However, for an existing element that was changed it tries calling put. The rest interface I'm working with does not have a put command, instead it uses post with an element id to update that element.
Is there an easy way to make the save method realize that I want it to use post, with the element id, instead of put when I call save on the method? do I have to overwrite the method entirely?
Incidentally, as best I can tell rectangular uses POST for new elements, and PUT if the element had previously existed, but I'm not certain of that. Can anyone tell me how rectangular decides which call is appropriate? the documentation just says it will 'decide' which to call.
EDIT:
I found a very simple solution to this, that worked well in my case because the REST interface we were connecting to didn't use PUT's anywhere. I added the following line to our initialization factory:
Restangular.setMethodOverriders(["put", "post"]);
effectively this changed every put call to a post call. Since our format was restful, other then not using Puts, this worked well. We can now simply call save on any restangularized element and it will just work.
回答1:
I checked the Restangular source and found the following:
function save(params, headers) {
if (this[config.restangularFields.fromServer]) {
return this[config.restangularFields.put](params, headers);
} else {
return _.bind(elemFunction, this)('post', undefined, params, undefined, headers);
}
}
So, Restangular differs between javascript objects that you created and restangularized, and those you got via a Restangular method (flavors of the get
method). If it is the first it uses POST
, because locally restangularizing an element implies that it doesn't exist in the remote location. After the first save or if you pulled it from a remote source, it will use PUT
.
This behavior fits REST very well, because POST
for creation of objects and PUT
for the updates is an frequently used approach for REST APIs. See this section from Wikipedia on REST for an example.
For your specific situation, there are (at least) following two solutions:
Update the API to allow PUTs
for updates if you have access to it or generally use the post
method of your restangularized elements. I would suggest not to directly change the config.restangularFields.fromServer
field or to override the save
method of Restangular (although both should work).
来源:https://stackoverflow.com/questions/29305772/control-when-put-vs-post-is-called-with-restangular-save-method