Search code examples
angularjsangular-resource

How do I override Angular $resource save?


I have created a service like so:

fbApp.factory('Post', ['$resource',
function ($resource) {
    return $resource('posts/:postId', {}, {
        query: {method: 'GET', params: {postId: 'index'}, isArray: true}
    });
}]);

In my controller I am saving new posts like so:

var postData = angular.copy($scope.formData);
postData.published = $filter('date')($scope.formData.published, 'yyyy-MM-dd HH:mm:ss', 'UTC');
var post = new Post({Post:postData});
post.$save();

I want to change the service's save method so that instead of new Post({Post:postData}).$save() I can simply do new Post(postData).$save(). I took a look at https://docs.angularjs.org/api/ngResource/service/$resource and I believe the key is to override the $resource.$save() method or use transformRequest. Documentation on either is lacking.


Solution

  • The save method let you pass custom data to the request.

    angular.module('myApp').factory('myFactory', function($resource){
       return $resource ('api/comments/');
    });
    
    angular.module('myApp').controller('myController', function($scope, myFactory){
       $scope.myData = 'some data';
    
       myFactory.save($scope.myData, function(){
          //do something useful.
       });
    });
    

    UPDATE

    app.config(function($httpProvider) {
    
    $httpProvider.defaults.transformRequest = function(data){
        //do something here
    }
    
    });