0

I want to use angular resource to interact with my rails backend, the build-in $resource service is not fully compatible with rails API, like PUT is not support by default, I have to add custom action "update" with PUT method.

This problem with this approach is I have to add update action for every resource to make angular resource align with the rails API backend.

Is this the good approach to go?

I also found a angular resource wrapper angularjs-rails-resource, which provide a update method with PUT http verb, but it seems like the way how it handle parameters passing is a bit odd. for example, it wrap the parameter with a "undefined" key.

Parameters: {"undefined"=>{"username"=>"xxxx"}, "version"=>"1", "id"=>"88"}

So, the question is what is the best practice to use angular resource with rails API?

fuyi
  • 2,573
  • 4
  • 23
  • 46

3 Answers3

1

If you don't want the overhead of restangular and just want to add the update method to every resource, you can simply add a decorator to the $resource service.

Something like this:

.config(function ($provide) {
    $provide.decorator('$resource', function ($delegate) {

        //Store the delegate, so we can access it later
        var resourceFactory = $delegate;

        //Add the actions that you want added to each Resource here
        var default_actions = {'update': {method: 'PUT'}};

        return function (url, paramDefaults, actions) {
            actions = angular.extend({}, default_actions, actions);
            return resourceFactory(url, paramDefaults, actions);
        };

    });
})
daviddan
  • 416
  • 2
  • 8
  • Thank you, I think this is the easiest way to add default actions to all resources – fuyi Apr 21 '14 at 20:01
  • How would I add method which return $resource instance, but not making a ajax call to backend? – fuyi Apr 24 '14 at 07:39
1

Use angular-rails-resource. It is optimized for the Rails philosophy, which means that you don't have to juggle around with request/response format by yourself. And it supports a lot of other cool features, like nested resources, automatic name conversion, etc...

Nikola M.
  • 573
  • 6
  • 16
0

Take a look on restangular. It's really a nice solution for interacting with rest api.

jalkoby
  • 379
  • 1
  • 4