Last Updated: April 18, 2016
·
38.8K
· petrbela

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

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

over 1 year ago ·

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 ·

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

over 1 year ago ·

Nice stuff. Thank u

over 1 year ago ·