rd0c8w
Last Updated: April 18, 2016
·
30.32K
· petrbela
D1d8b6e6a25f6fa7bc5f89bc33aa3422

RESTful $resource in AngularJS

$resource is a useful service that helps you interact with a REST API from your AngularJS application.

$resource by default handles these five REST operations to (1) get a list of items, (2) get an item, (3) insert an item, (4) update an item, and (5) delete an item:

(1) GET /collection
(2) GET /collection/:id
(3) POST /collection
(4) PUT /collection/:id
(5) DELETE /collection/:id

However, this might not be enough for you. Rails enables you to define additional actions on your resources, but how to wire them to $resource?

Turns out the solution is pretty simple:

angular.module('myApp')
.factory('Station', ['$resource', 'apiUrl', ($resource, apiUrl) ->
  Station = $resource(apiUrl + '/stations/:collectionRoute:id/:memberRoute', {
    id: '@id'
    collectionRoute: '@collectionRoute'
    memberRoute: '@memberRoute'
  }, {
    # Define methods on the Station object

    # /stations/autocomplete?term=Pra
    # Invoke as: Station.autocomplete({term: 'Pra'})
    autocomplete: {method: 'GET', isArray: true, params: {collectionRoute: 'autocomplete'}}

    # /stations/123/location
    # Invoke as: Station.location({id: 123})
    location: {method: 'GET', params: {memberRoute: 'location'}}
  })
  return Station
])

$resource automatically binds id, collectionRoute and memberRoute params into the URL, and all other params as query params (?param=).

By wiring the collectionRoute/memberRoute params to custom methods, you can now call Station.autocomplete({term: 'Pra'}) as a collection action, and Station.location({id: 123}) as a member action.

P.S. Kudos to http://www.bennadel.com/blog/2433-Using-RESTful-Controllers-In-An-AngularJS-Resource.htm, which was the original source for this tip.

4 Responses
Add your response

6537
5cfe483d7afdaf422ef0e16a0f0ac176

Restangular (https://github.com/mgonto/restangular) is also a good service to handle rest request. Worth a look.

over 1 year ago ·
13428
638fa0a11d0cb897a6dab71bfdcacf49

I really didn't like the fact that restangular depends on lodash, and that it's not pre-configurable.
So I tried to create my own module which extends Angular's resource object to support nested models:
https://github.com/roypeled/angular-nested-resource

over 1 year ago ·
15032
0 uuv 7saljy fda6wamnd74wljx5owt6wasts7jd9gylvn9adhe5o3mg41clzhvf5s7b28yuyr9zq

Thank you very much! In a few words you cleared me everything!

over 1 year ago ·
15756
Qubvseyu normal

Nice stuff. Thank u

over 1 year ago ·