How to set only some fields using Restangular?

Say I have a resource with several fields, and some of them are read-only. Or maybe they belong to different use cases that I would like to handle differently on the server.

For example, my bing resource looks like this:

 {id: 1, foo: "A", bar: "B", createdAt: "2013-05-05"} 

I would like to get Restangular for PUT for only some fields, by performing queries such as:

 PUT /bing/1 {foo: "A"} PUT /bing/1 {bar: "B"} PUT /bing/1 {foo: "A", bar: "B"} 

I want to do not :

 PUT /bing/1 {id: 1, foo: "A", bar: "B", createdAt: "2013-05-05"} 

How can i achieve this?

+6
source share
3 answers

I am the creator of Restangular.

@ Nicholas is absolutely right :). This is PATCH, not PUT. And Restangular supports it :).

elem.patch({foo: 2}) is the path if elem is already a restangularized object.

Hope this helps!

+22
source

What a PATCH not a PUT .

See https://tools.ietf.org/html/rfc5789

+6
source

One way to do this is to pass the entire object to the patch method, including all fields that you do not want to send to the server, and then use the request interceptor to remove any unwanted fields before the request is sent.

For example, to always remove the createdAt field from any patch request, you could do something like

 app.config(function(RestangularProvider) { RestangularProvider.setRequestInterceptor(function(element, operation, route, url) { if (operation === 'patch') { delete element.createdAt; return element; } }); }); 

To learn more about request interceptors, see the documentation for setRequestInterceptor

+2
source

Source: https://habr.com/ru/post/951297/


All Articles