Pregunta

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?

¿Fue útil?

Solución

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

    });
})

Otros consejos

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...

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top