在我的 Angular 应用程序中,我有一项服务利用$http
从服务器检索数据。服务器端点使用 HMAC 身份验证,并期望查询字符串参数按 URL 上的特定顺序排列。
角度排序$http构建 URL 时的参数 https://github.com/angular/angular.js/blob/v1.3.14/src/ng/http.js#L1135,所以似乎不可能指定自定义参数顺序。
这是一个例子:
this.apiCall = function() {
return $http({
method: 'GET',
url: 'http://example.com/url/v1/endpoint',
params: {
'c': 'cdata',
'a': 'adata',
'b': 'bdata'
}
});
};
Angular 会将 URL 构建为http://example.com/url/v1/endpoint?a=adata&b=bdata&c=cdata
,但我需要保留指定的参数顺序,http://example.com/url/v1/endpoint?c=cdata&a=adata&b=bdata
.
我意识到我可以手动将参数附加到 URL 字符串,但这不是很友好,并且不允许在$http
拦截器。
Angular 可能会对参数进行排序,以在浏览器实现之间保持统一的行为,因为 ECMAScript 中未指定对象排序。
不管,有谁知道如何解决对参数进行排序的默认 Angular 行为,以便构建一个保留指定参数的 URL?
我改进了您的解决方案,以创建更精简且保证有效的解决方案:
$httpProvider.interceptors.push(function() {
return {
request: function (config) {
if (!config.paramOrder) {
return config;
}
// avoid leaking config modifications
config = angular.copy(config, {});
var orderedParams = [];
config.paramOrder.forEach(function (key) {
if (config.params.hasOwnProperty(key)) {
orderedParams.push(encodeURIComponent(key) + '=' + encodeURIComponent(config.params[key]));
// leave only the unordered params in the `params` config
delete config.params[key];
}
});
config.url += (config.url.indexOf('?') === -1) ? '?' : '&';
config.url += orderedParams.join('&');
return config;
},
};
});
使用以下命令调用:
$http({
method: 'GET',
url: 'http://example.com/url/v1/endpoint',
params: {
a: 'aValue',
b: 'bValue',
c: 'cValue'
},
paramOrder: ['c', 'a']
});
获取以 key 开头的查询字符串c
其次是a
。中未提及的参数paramOrder
将附加在有序参数之后(按字母顺序)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)