动态绑定AngularJS中$ http服务的URL参数

时间:2014-04-17 11:56:20

标签: angularjs http angularjs-service

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

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

1 个答案:

答案 0 :(得分:0)

通用函数,将第一个参数作为带有占位符的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);