如何使用经过身份验证的用户的 id 更新 angular 资源 url?

How to update angular resource urls with id from the authenticated user?

所以我用 ngResource 定义了多个 angular 工厂,类似于:

.factory('factoryName', ['$resource', '$http', 'CONSTANTS', 'authService', factoryNameCtrl])
function factoryNameCtrl($resource, $http, CONSTANTS, authService) {
    var actions = {
        'get': {
            method: 'GET',
            isArray: false,
            params: {
                service: '@service',
                action: '@action'
            }
        },
        'post': {
            method: 'POST',
            isArray: false,
            params: {
                service: '@service',
                action: '@action'
            }
        }
    }
    actions.get.params.userId = actions.post.params.userId = '@' + authService.currentUser.id;
    var res = $resource(CONSTANTS.baseURL + '/:userId/integrations/:service/:action', {}, actions);

如果我用另一个用户登录和注销,工厂内的 userId 值不会更新。

我不想将 userId 传递到我所有代码的每个参数中,而是要在它发生变化时使其可用。

以前我有下面的代码,我强制重新加载页面以将正确的 url 重建到资源中。

if (authService.isAuthenticated()) {
        var res = $resource(CONSTANTS.baseURL + '/' + authService.currentUser.id + '/integrations/:service/:action', {}, actions);
        return res;
    }

你有什么建议?

要每次都重新计算它,请使用一个函数:

actions.get.params.userId = function () {
    return computeCurrentUserId();
};

来自文档:

If a parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).

-- AngularJS $resource API Reference