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?

3 Answers 3

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

    });
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I think this is the easiest way to add default actions to all resources
How would I add method which return $resource instance, but not making a ajax call to backend?
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...

Comments

0

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

1 Comment

Thanks, restangular is a interesting extension of $resource

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.