【问题标题】:Dynamically bind URL params for $http service in AngularJS在 AngularJS 中为 $http 服务动态绑定 URL 参数
【发布时间】:2014-06-01 16:26:19
【问题描述】:

如何动态填充 URL 字符串中定义的占位符,用于 AngularJS $http 服务的 HTTP 请求?

var urls = {
    GET_USER: '/api/v1/group/{groupId}/user/{userId}',
    GET_USER_POSTS: '/api/v1/group/{groupId}/user/{userId}/posts',
    GET_USER_POST: '/api/v1/group/{groupId}/user/{userId}/post/{postId}'
};

function getUser(groupId, userId) {
    var url = urls.GET_USER; // build URL with passed params somehow
    return $http.get(url);
}

【问题讨论】:

    标签: angularjs http angularjs-service


    【解决方案1】:

    接受第一个参数作为带有占位符的 URL 并使用传递的参数构建 URL 字符串的通用函数

    function buildUrl(url) {
        if (arguments.length > 1) {
            var args = arguments, i = 1;
            return url.replace(/{\w+?}/g, function () {
                return args[i++];
            });
        }
        return url;
    }
    

    用法:

    var url = buildUrl(urls.GET_USER, groupId, userId);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 2015-12-13
      • 2015-12-10
      • 1970-01-01
      相关资源
      最近更新 更多