gpt4 book ai didi

angularjs - 插入或取消转移到 $http 的 transformRequest 数组中(非全局)

转载 作者:行者123 更新时间:2023-12-04 09:31:15 27 4
gpt4 key购买 nike

请参阅已接受的回答 here对 transFormRequest 函数/数组的一个很好的解释。

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

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)
}

或者,如果您希望在 angular 的默认转换之后进行自定义转换。
{
transformRequest: $http.defaults.transformRequest.concat([function(req){...}])
}

关于angularjs - 插入或取消转移到 $http 的 transformRequest 数组中(非全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com