【问题标题】:Remove or override request interceptor for scoped configuration in Restangular在 Restangular 中删除或覆盖范围配置的请求拦截器
【发布时间】:2016-01-13 22:33:09
【问题描述】:

我正在使用 Restangular 在单页 Angular Web 应用程序中处理我的令牌/标头身份验证。 使用 addFullRequestInterceptor,我为每个传出的 REST API 调用设置正确的标头,使用个人密钥加密数据。

Restangular
        .setBaseUrl(CONSTANTS.API_URL)
        .setRequestSuffix('.json')
        .setDefaultHeaders({'X-MyApp-ApiKey': CONSTANTS.API_KEY})
        .addFullRequestInterceptor(requestInterceptor)
        .addErrorInterceptor(errorInterceptor);

function requestInterceptor(element, operation, route, url, headers, params, httpConfig) {
        var timeStamp = Helpers.generateTimestamp(),
            //Condensed code for illustration purposes
            authSign = Helpers.generateAuthenticationHash(hashIngredients, key, token),
            allHeaders = angular.extend(headers, {
                'X-MyApp-Timestamp': timeStamp,
                'Authentication': authSign
            });

        return {
            headers: allHeaders
        }
    }

效果很好。但我需要一个例外:对于尚未登录的新访问者,通过 REST 请求通用密钥/令牌对。此密钥/令牌对用于登录身份验证调用的标头中。 所以对于这个调用,我创建了一个单独的 Restangular 子配置。在此配置中,我想覆盖 requestInterceptor。但这似乎被忽略了(即仍然调用原始拦截器)。我传递 null 或返回空对象的函数都没有关系。

var specialRestInst = Restangular.withConfig(function(RestangularConfigurer) {
                RestangularConfigurer.addFullRequestInterceptor(function() {return {}});
            }),
            timeStamp = Helpers.generateTimestamp(),
            header = {'X-MyApp-Timestamp': timeStamp};

        specialRestInst.one('initialise').get({id: 'app'}, header)

因此,正如 Restangular 所记录的,withConfig 采用了基本配置并对其进行了扩展。我想知道如何删除FullRequestInterceptor(这个函数不存在),覆盖它,或者类似的东西。

【问题讨论】:

    标签: javascript angularjs restangular


    【解决方案1】:

    我会采取不同的方法并尝试将标志传递给拦截器。如果标志存在,则排除authSign。您可以使用withHttpConfig 执行此操作。最好在特殊情况下排除,然后总是告诉拦截器包含authSign

    所以你会像这样更新拦截器。

    function requestInterceptor(element, operation, route, url, headers, params, httpConfig) {
        var timeStamp = Helpers.generateTimestamp();
        var allHeaders = {'X-MyApp-Timestamp': timeStamp};
        if(!httpConfig.excludeAuth) {
            //Condensed code for illustration purposes
            var authSign = Helpers.generateAuthenticationHash(hashIngredients, key, token);
            allHeaders['Authentication'] = authSign;
        }
        return angular.extend(headers, allHeaders);
    }
    

    当您需要排除 authSign 时,您可以像这样使用 restangular。

    specialRestInst.withHttpConfig({excludeAuth: true}).get({id: 'app'});
    

    您应该能够将任何值添加到您想要的 http 配置中,只要它们尚未使用。

    我不确定这是否会按预期工作,但我不明白为什么它不起作用。

    【讨论】:

    • 我猜这是一个选项。我已经设法通过检测route-参数来解决这个问题。但是如果可以进行子配置,我希望拦截器可以被覆盖。所以我希望有人知道如何(或知道为什么这是不可能的)。
    猜你喜欢
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2020-09-08
    • 2014-05-29
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多