how to set custom headers with a $resource action?

前端 未结 5 1600
谎友^
谎友^ 2020-12-03 04:37

with $http, we can do this:

var config = { headers: { \'something\': \'anything\' } };          
$http.get(\'url/to/json\', config)
    .success(function()          


        
5条回答
  •  执笔经年
    2020-12-03 04:54

    You can set dynamic one-off headers by accessing the config API object in the resource

    Demo Code

    angular.
    .factory('Resource',['$resource',function($resource){return $resource(baseUrl+'/resource/:id', {id: '@_id'}, {
    update    : {
      method  : 'POST',
      url     : baseUrl+'/resource/:id',
      headers : {
        'custom-header': function(config) {
          // access variable via config.data
          return config.data.customHeaderValue;
        }
      },
      transformRequest: function(data) {
        // you can delete the variable if you don't want it sent to the backend
        delete data['customHeaderValue'];
        // transform payload before sending
        return JSON.stringify(data);
      }
    } 
    });
    }]);
    

    To execute

    Resource.update({},{
      customHeaderValue: setCustomHeaderValue
    },
    function (response) {
      // do something ...
    },function(error){
      // process error
    });
    

提交回复
热议问题