Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the URL requested by the Angular $resource service

Tags:

angularjs

I use the Angular $resource service to make HTTP calls such as

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

at the point indicated by the comment, is there some way to get the URL that the request was submitted to, which in the example above would be http://example.org/6

like image 311
Little Bobby Drop Tables Avatar asked Dec 07 '25 07:12

Little Bobby Drop Tables


2 Answers

You can add an interceptor to your GET request, and attach the url to the response data. For example, you could do the following:

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);
});
like image 86
Sha Alibhai Avatar answered Dec 12 '25 13:12

Sha Alibhai


I cannot think of any direct way of retrieving the url from looking at the docs of $resource. An alternative but not optimal way to do it is by using the $httpParamSerializer to encode the data again and append that to the url to recreate the one that was used when sending the request.

like image 37
Ali Al Amine Avatar answered Dec 12 '25 14:12

Ali Al Amine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!