Prevent ngResource from requiring a returned item on $save

牧云@^-^@ 提交于 2019-12-02 15:43:18

问题


It seems that when I $save or use a custom $update (put or post) method on my resource that it expects the newly posted document to be returned. I don't want to return anything from my save/post ops but an ok/200/error type of statement but doing so causes the item to be blank as soon as saved.

var item = Things.get({
 id: $route.current.params.id
}, function() {
 console.log(item);  // Item is ok
}); 

var item = Things.get({
 id: $route.current.params.id
}, function() {
 console.log(item);  // Item is blank (because server returned just 'ok')
 item.$save();
}); 

回答1:


When you do a $save() there will be a validation to check if there is any data returned and if thats the case, the response will be copied to the original object (in your case item)

This is the callback when receiving a response from server:

var promise = $http(httpConfig).then(function(response) {
  var data = response.data,
      promise = value.$promise;

  if (data) {
    // Need to convert action.isArray to boolean in case it is undefined
    // jshint -W018
    if (angular.isArray(data) !== (!!action.isArray)) {
      throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected ' +
        'response to contain an {0} but got an {1}',
        action.isArray?'array':'object', angular.isArray(data)?'array':'object');
    }
    // jshint +W018
    if (action.isArray) {
      value.length = 0;
      forEach(data, function(item) {
        value.push(new Resource(item));
      });
    } else {
      shallowClearAndCopy(data, value);
      value.$promise = promise;
    }
  }

  value.$resolved = true;

  response.resource = value;

  return response;
}, function(response) {
  value.$resolved = true;

  (error||noop)(response);

  return $q.reject(response);
});

You can check full source code here

So if you don't want to have your object overwritten, then just don't send any data on the response from server.




回答2:


If your server returns a 204 (no-content), it won't replace the resource once the save is complete.



来源:https://stackoverflow.com/questions/21471059/prevent-ngresource-from-requiring-a-returned-item-on-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!