在AngularJS$资源模块上请求之前获取URL

Getting the URL before making the request on AngularJS $resource module

本文关键字:获取 URL 请求 AngularJS 资源 模块      更新时间:2023-10-28

我使用Angular JS,使用$resource模块来使用RESTapi。我必须使用私钥对URL进行编码,并在标头上发送编码过程的结果。我正在尝试拦截请求并获取请求的URL,但我无法做到这一点。

return $resource(url, {}, {
    get: { method: 'GET', headers: headers, transformRequest: function(data, headersGetter) {
        // Here "data" is undefined.  headersGetter() returns the headers. 
        // I need the URL here
    } 
});

有什么帮助吗?

听起来你想要的是一个拦截器。查找$http文档的Interceptors部分。它看起来像这样:

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
        // optional method
        'request': function(config) {
            //modify headers in config based on url in config
            return config;
        },
    }
});

然后像这样注册拦截器:

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myHttpInterceptor');
}]);