Is it possible to specify parameter order with Angular's $http service?

ぃ、小莉子 提交于 2019-12-05 20:08:35

I improved upon your solution to create something more stream-lined and guaranteed to work:

$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;
        },
    };
});

Invoke with the following:

$http({
    method: 'GET',
    url: 'http://example.com/url/v1/endpoint',
    params: {
        a: 'aValue',
        b: 'bValue',
        c: 'cValue'
    },
    paramOrder: ['c', 'a']
});

to get a query string starting with key c followed by a. The params not mentioned in paramOrder will be appended after the ordered params (in alphabetical order).

I ended up creating a rudimentary interceptor to keep the "as-specified" params order. This interceptor runs if the keepParamsOrder configuration variable is set on the $http call.

In your module config:

$httpProvider.interceptors.push(function() {
    return {
        'request': function(config) {
            if (!config.keepParamsOrder || !config.params) {
                return config;
            }

            var queryStrings = [];
            for (var key in config.params) {
                if (config.params.hasOwnProperty(key)) {
                    queryStrings.push(key + '=' + config.params[key]);
                }
            }

            // Reset the params to be empty
            config.params = {};

            config.url += (config.url.indexOf('?') === -1) ? '?' : '&';
            config.url += queryStrings.join('&');

            return config;
        },
    };
});

Tell it to run in the service call config:

this.apiCall = function() {
    return $http({
        method: 'GET',
        url: 'http://example.com/url/v1/endpoint',
        params: {
            'c': 'cdata',
            'a': 'adata',
            'b': 'bdata'
        },
        keepParamsOrder: true
    });
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!