Default $resource POST data

前端 未结 7 1233
天命终不由人
天命终不由人 2021-02-07 11:51

That might be strange but I need to specify some default POST data for my $resource using the factory method of the module.

Does anyone have an idea of how to do that in

7条回答
  •  名媛妹妹
    2021-02-07 12:17

    You can set default fields on your request by using transformRequest option for your $resource's actions that use the POST method.

    For example something like this

    function prependTransform(defaults, transform) {
    
     // We can't guarantee that the default transformation is an array
     defaults = angular.isArray(defaults) ? defaults : [defaults];
    
     // Append the new transformation to the defaults
     return [transform].concat(defaults);
    }
    
    ctrl.factory('MyResource', ['$resource', '$http',
    function($resource, $http) {
        return $resource('/path/to/myresource/:id', {id : '@id'},
               { 
                   create : {
                       method : 'POST',
                       transformRequest : prependTransform($http.defaults.transformRequest,
                          function(data, headers) {
                               return addDefaultField(data);
                          }
                      ),
                   },
               });
        }
    ]);
    

提交回复
热议问题