加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 推送或取消进入$http(非全局)的transformRequest数

发布时间:2020-12-17 07:22:14 所属栏目:安全 来源:网络整理
导读:有关transFormRequest函数/数组的相当好的解释,请参阅 here的已接受答案. 在答案的最后一个例子中: var transform = function(data){ return $.param(data);}$http.post("/foo/bar",requestData,{ headers: { 'Content-Type': 'application/x-www-form-urle
有关transFormRequest函数/数组的相当好的解释,请参阅 here的已接受答案.

在答案的最后一个例子中:

var transform = function(data){
    return $.param(data);
}

$http.post("/foo/bar",requestData,{
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},transformRequest: transform
}).success(function(responseData) {
    //do stuff with response
});

但是,这个问题是transformRequest:transform会覆盖Angular预先构建的函数数组.

来自Angular docs:

To globally augment or override the default transforms,modify the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties. These properties are by default an array of transform functions,which allows you to push or unshift a new transformation function into the transformation chain. You can also decide to completely override any default transformations by assigning your transformation functions to these properties directly without the array wrapper. These defaults are again available on the $http factory at run-time,which may be useful if you have run-time services you wish to be involved in your transformations.

Similarly,to locally override the request/response transforms,augment the transformRequest and/or transformResponse properties of the configuration object passed into $http.

如果我想全局应用我的变换函数,我会这样做

$httpProvider.defaults.transformRequest.unshift(myFunction)

要么

$httpProvider.defaults.transformRequest.push(myFunction)

我的问题
如何将另一个转换函数推送到调用而不是全局?而不是擦除整个转换请求函数数组?

我找到了一个使用.concat方法的简单解决方案
{
   transformRequest: [function(req){...}].concat($http.defaults.transformRequest)
}

或者,如果您希望在角度的默认转换后进行自定义转换.

{
   transformRequest: $http.defaults.transformRequest.concat([function(req){...}])
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读