在restangular中为单个请求设置标头和http参数

use*_*226 8 post file-upload angularjs restangular

我正在尝试使用restangular进行文件上传请求,我想在restangular中实现与下面相同的功能.但是,我不确定如何为此特定请求设置内容类型和transformRequest.如果我理解正确,setDefaultHeader会为所有后续请求设置它.还有其他方法吗?

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(){
      });
     }
}]);
Run Code Online (Sandbox Code Playgroud)

fer*_*sik 8

这里有2种情况,POST用于创建新项目或PUT用于编辑项目:

// 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');
    });
Run Code Online (Sandbox Code Playgroud)


JDW*_*dle 6

要为单个请求设置标头,您需要做的就是添加一个包含标头名称和值的对象作为.post(),. get()的参数或您需要的任何方法.

https://github.com/mgonto/restangular#element-methods

Restangular.all('some-endpoint').post(postContent, {}, {'Content-Type': undefined}).then(function (response) {
    console.log('Weeeeee!!!');
});
Run Code Online (Sandbox Code Playgroud)

至于我不确定的transformRequest,我之前没有处理过类似的事情,这是我在文档中唯一可以找到的东西:

https://github.com/mgonto/restangular#setdefaulthttpfields

但这似乎是为所有要求设定的,这不是你想要的,但它至少是这样的.

无论如何,希望这将有助于你得到你想要的.

编辑:

由于restangular中的大多数请求类型都有一个查询参数,然后您需要传递一个空白查询参数对象然后标题,所以示例已经更新以显示此信息.


jos*_*rry 5

由于这是此问题首次出现在Google上,请参阅Restangular问题跟踪器中的问题420.

基本上,最新的Restangular具有在分派请求之前withHttpConfig设置$http选项的功能.

如果您在某个URL上有一条路线,example.com/api/users/:id/picture那么接受带有特定用户图像的分段上传,您可以执行以下操作:

Users.one(2)
    .withHttpConfig({transformRequest: angular.identity})
    .customPOST(filedata, 'picture', undefined, {'Content-Type': undefined})
    .then(function(resp) {
        // File data post is complete here
    });
Run Code Online (Sandbox Code Playgroud)

默认情况下,Angular会将发送的任何数据转换$http为JSON.在transformRequest配置简单地替换为一个是默认的转换NOP.