How to use the PUT method in restangular

I use restangular, but I have a problem with the "Put" method, but it does not work as expected

My angular service code

var userService = function (restangular) { var resourceBase = restangular.all("account/"); restangular.addResponseInterceptor(function (data, operation, what, url, response, deferred) { if (operation == "getList") { return response.data; } return response; }); this.getUserById = function (id) { return resourceBase.get(id); // return restangular.one("account", id).get(); }; this.updateUser = function(user) { return user.Put(); }; } 

My controller code

  var userEditController = function (scope, userService, feedBackFactory, $routeParams) { scope.user = undefined; scope.updateUser = function () { userService.updateUser(scope.user).then(function (data) { feedBackFactory.showFeedBack(data); }, function (err) { feedBackFactory.showFeedBack(err); }); }; userService.getUserById($routeParams.id).then(function (data) { scope.user = data.data; **// Please not here I am reading the object using service and this object is getting updated and pass again to the service for updating** }, function (er) { feedBackFactory.showFeedBack(er); }); }; 

but I get the error message “Put” is not a function, I checked the user object and I found that the user object is not restangularized (no additional methods were found). How can i solve this problem

+6
source share
2 answers

You can only "put" on the data object.

customPUT([elem, path, params, headers]) is what you want. use it as follows:

 Restangular.all('yourTargetInSetPath').customPUT({'something': 'hello'}).then( function(data) { /** do something **/ }, function(error) { /** do some other thing **/ } ); 
+10
source

You can use the put method only in restangularized objects. To run an object on an object, you need to check the put method, if the object does not contain the put method, then you need to convert this object to a restangularized object.

Change your updateUser as follows:

  this.updateUser = function(user) { if(user.put){ return user.put(); } else { // you need to convert you object into restangular object var remoteItem = Restangular.copy(user); // now you can put on remoteItem return remoteItem.put(); } }; 

The restangular.copy method will add some extra rechan methods to the object. In short, it converts any object to a restangularized object.

+2
source

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


All Articles