Search code examples
ruby-on-railsangularjsruby-on-rails-4angular-resourcerails-api

How to use angular resource with rails API


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?


Solution

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