Setting headers and http params for a single request in restangular

user760226 picture user760226 · Jan 22, 2014 · Viewed 20k times · Source

I am trying to use restangular for file upload post request , I want to achieve the same functionality as below in restangular. However, I was unsure how to set content type and transformRequest for just this particular request. If I understand correctly, setDefaultHeader sets it for all subsequent requests. Is there some other way?

myApp.service('$fileUpload', ['$http', function ($http) {
   this.uploadFileToUrl = function(file, uploadUrl){
      var filedata = new FormData();
      filedata.append('file', file);
      $http.post(uploadUrl, filedata, {
         transformRequest: angular.identity,
         headers: {'Content-Type': undefined}
      })
      .success(function(){
      })
      .error(function(){
      });
     }
}]);

Answer

fernandopasik picture fernandopasik · May 15, 2014

You have 2 situations here, the POST for create a new item or the PUT to edit an item:

// Save new Item
$scope.saveNew = function (item) {

  var data = new FormData();
  angular.forEach(item, function (fieldData, field) {
    data.append(field, fieldData);
  });

  Restangular
    .all('items')
    .withHttpConfig({transformRequest: angular.identity})
    .post(data, {}, {'Content-Type': undefined})
    .then(function () {
      // do on success
    }, function () {
      // do on failure
    });
};

// Edit existing Item
$scope.save = function (item) {

  var data = new FormData();
  angular.forEach(item.plain(), function (fieldData, field) {
    data.append(field, fieldData);
  });

  Restangular
    .one('items', item._id)
    .withHttpConfig({transformRequest: angular.identity})
    .customPUT(data, undefined, {}, {'Content-Type': undefined})
    .then(function () {
      $location.path('sites');
    });