How do I add a custom method to a restangular service?

Issue

I have a decoupled Restangular service which I’d like to attach a custom method to. It appears that the only methods returned on a collection by default are getList, one, and post. I would like to do Locations.getLongLat()

I have tried adding the following to my service with no luck (the method isn’t bound to the object) and I just get undefined is not an object in response.

angular.module('myApp')
.factory('Locations', function (Restangular) {

    return Restangular.withConfig(function (RestangularConfigurer) {
        RestangularConfigurer.addElementTransformer('api/v1/locations', true, function (location) {
            location.addRestangularMethod('getLongLat', 'get', 'longlat');
            return location;
        });
    }).service('api/v1/locations');
})

Anyone have any ideas?

Solution

Just in case anyone was wondering how I resolved this – custom methods alongside a service is actually unsupported in the master branch of Restangular. Calling service will just override the collection and any custom methods applied prior to this with the defaults.

To resolve I’ve overrided the toService function to support custom methods.

Answered By – David Wadge

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.