3

How can I get the url (and params) from an ng-resource?

And if that is not possible how can I create a wrapper or extend ng-resource so I get this functionality?

Update: I want to be able to extract the URL and params from the resource object without ever sending a request.

In an ideal world the following works:

myResource = $resource('localhost/foo/bar');

myResource.getUrl() // returns localhost/foo/bar

Since the getUrl function doesn't exist I tried the following I found in https://stackoverflow.com/a/28474289/4829972

A wrapping factory:

angular.module('app').factory('ExtendedResourceFactory',['$resource',
  function($resource) {
    function ExtendedResourceFactory() {
      var Resource = $resource.apply(this, arguments);

      Resource.prototype.getArguments = function() {
        return arguments
      };

      return Resource;
    }

    return ExtendedResourceFactory;
  }
]); 

I inject the new factory and try it out:

res = ExtendedResourceFactory('url')
res.getArguments()

Uncaught TypeError: res.getArguments is not a function(…) 

Thankful for directions or solutions!!

Community
  • 1
  • 1
alfthan
  • 463
  • 4
  • 13
  • I need that also for unit testing. I would like to do : `$httpBackend.expectGET(MyResource.getUrl()).respond(200, fixture.get)` – Ludo Jun 21 '16 at 15:43

2 Answers2

0

Maybe the following will be of use. Since you have explicit control of the URL being passed into $resource, I assume you can transform the response to provide the function you desire. It is by no means clean, but does appear functional.

var resource;

resource = $resource('/foo/bar', 
  {
    id: 1
  }, {
    get: {
      method: 'GET',
      transformResponse: function(data) {
        data = angular.fromJson(data);
        data.getUrl = function() {
          return '/foo/bar';
        };
        return data;
      }
    }
  }
);
G Klausner
  • 11
  • 2
  • Thank you! With this solution I would have to call the get method in order for the getUrl function to be exposed. The question was probably not clear enough. What I want to achieve is a way to extract the urls and params from the resource element without ever hitting the endpoint. – alfthan Apr 29 '16 at 09:16
0

It looks like NgResource stores all the internal variables and URLs inside its own scope, making it impossible to access them from the outside.

What you could do is to extend your $resource with additional information that you provide. Using this method you can have your URL (or any property) alongside your resource.

myResource = angular.extend(
    $resource('localhost/foo/bar'),
    { 
        getUrl: function() { return 'localhost/foo/bar'; }
    }
);
myResource.getUrl() // returns localhost/foo/bar