获取Angular $资源服务请求的URL

时间:2016-02-11 18:03:14

标签: angularjs

我使用Angular $resource服务进行HTTP调用,例如

var reportEndpoint = $resource('http://example.org/:id');

reportEndpoint.get({id: 6}, function (response, responseHeaders) {
    $scope.report = response.data;
    // can I get here the URL that the request was submitted to
});

在评论指出的位置,是否有某种方法可以获取请求提交到的网址,在上面的示例中将是http://example.org/6

2 个答案:

答案 0 :(得分:2)

您可以向GET请求添加拦截器,并将url附加到响应数据。例如,您可以执行以下操作:

var reportEndpoint = $resource('http://example.org/:id', {}, {
  get: {
    method: 'GET',
    interceptor: {
      response: function (response) {
        response.data.responseUrl = response.config.url;
        return response.data;
      }
});

reportEndpoint.get({id: 6}, function (response) {
  $scope.report = response;

  // returns http://example.org/6
  console.log($scope.report.responseUrl);
});

答案 1 :(得分:1)

我无法想到通过查看$ resource的文档来检索网址的任何直接方法。另一种但不是最佳的方法是使用$httpParamSerializer再次对数据进行编码,并将其附加到url以重新创建发送请求时使用的数据。

相关问题