Improve this Doc View Source $resource

  1. $resourceProvider
  2. service in module ngResource

Overview

A factory which creates a resource object that lets you interact with RESTful server-side data sources.

The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.

Requires the ngResource module to be installed.

By default, trailing slashes will be stripped from the calculated URLs, which can pose problems with server backends that do not expect that behavior. This can be disabled by configuring the $resourceProvider like this:

app.config(['$resourceProvider', function($resourceProvider) {
  // Don't strip trailing slashes from calculated URLs
  $resourceProvider.defaults.stripTrailingSlashes = false;
}]);

Dependencies

Usage

$resource(url, [paramDefaults], [actions], options);

Arguments

Param Type Details
url string

A parameterized URL template with parameters prefixed by : as in /user/:username. If you are using a URL with a port number (e.g. http://example.com:8080/api), it will be respected.

If you are using a url with a suffix, just add the suffix, like this: $resource('http://example.com/resource.json') or $resource('http://example.com/:id.json') or even $resource('http://example.com/resource/:resource_id.:format') If the parameter before the suffix is empty, :resource_id in this case, then the /. will be collapsed down to a single .. If you need this sequence to appear and not collapse then you can escape it with /\..

paramDefaults
(optional)
Object

Default values for url parameters. These can be overridden in actions methods. If a parameter value is a function, it will be called every time a param value needs to be obtained for a request (unless the param was overridden). The function will be passed the current data value as an argument.

Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.

Given a template /path/:verb and parameter {verb: 'greet', salutation: 'Hello'} results in URL /path/greet?salutation=Hello.

If the parameter value is prefixed with @, then the value for that parameter will be extracted from the corresponding property on the data object (provided when calling actions with a request body). For example, if the defaultParam object is {someParam: '@someProp'} then the value of someParam will be data.someProp. Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action method that does not accept a request body).

actions
(optional)
Object.<Object>=

Hash with declaration of custom actions that will be available in addition to the default set of resource actions (see below). If a custom action has the same key as a default action (e.g. save), then the default action will be overwritten, and not extended.

The declaration should be created in the format of $http.config:

{
  action1: {method:?, params:?, isArray:?, headers:?, ...},
  action2: {method:?, params:?, isArray:?, headers:?, ...},
  ...
}

Where:

  • action – {string} – The name of action. This name becomes the name of the method on your resource object.
  • method – {string} – Case insensitive HTTP method (e.g. GET, POST, PUT, DELETE, JSONP, etc).
  • params – {Object=} – Optional set of pre-bound parameters for this action. If any of the parameter value is a function, it will be called every time when a param value needs to be obtained for a request (unless the param was overridden). The function will be passed the current data value as an argument.
  • url – {string} – Action specific url override. The url templating is supported just like for the resource-level urls.
  • isArray – {boolean=} – If true then the returned object for this action is an array, see returns section.
  • transformRequest{function(data, headersGetter)|Array.<function(data, headersGetter)>} – Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. By default, transformRequest will contain one function that checks if the request data is an object and serializes it using angular.toJson. To prevent this behavior, set transformRequest to an empty array: transformRequest: []
  • transformResponse{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} – Transform function or an array of such functions. The transform function takes the HTTP response body, headers and status and returns its transformed (typically deserialized) version. By default, transformResponse will contain one function that checks if the response looks like a JSON string and deserializes it using angular.fromJson. To prevent this behavior, set transformResponse to an empty array: transformResponse: []
  • cache{boolean|Cache} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.
  • timeout{number} – Timeout in milliseconds.
    Note: In contrast to $http.config, promises are not supported in $resource, because the same value would be used for multiple requests. If you are looking for a way to cancel requests, you should use the cancellable option.
  • cancellable{boolean} – If true, the request made by a "non-instance" call will be cancelled (if not already completed) by calling $cancelRequest() on the call's return value. Calling $cancelRequest() for a non-cancellable or an already completed/cancelled request will have no effect.
  • withCredentials{boolean} – Whether to set the withCredentials flag on the XHR object. See XMLHttpRequest.withCredentials for more information.
  • responseType{string} – See XMLHttpRequest.responseType.
  • interceptor{Object=} – The interceptor object has four optional methods - request, requestError, response, and responseError. See $http interceptors for details. Note that request/requestError interceptors are applied before calling $http, thus before any global $http interceptors. Also, rejecting or throwing an error inside the request interceptor will result in calling the responseError interceptor. The resource instance or collection is available on the resource property of the http response object passed to response/responseError interceptors. Keep in mind that the associated promise will be resolved with the value returned by the response interceptors. Make sure you return an appropriate value and not the response object passed as input. For reference, the default response interceptor (which gets applied if you don't specify a custom one) returns response.resource.
    See below for an example of using interceptors in $resource.
  • hasBody{boolean} – If true, then the request will have a body. If not specified, then only POST, PUT and PATCH requests will have a body. *
options Object

Hash with custom settings that should extend the default $resourceProvider behavior. The supported options are:

  • stripTrailingSlashes – {boolean} – If true then the trailing slashes from any calculated URL will be stripped. (Defaults to true.)
  • cancellable – {boolean} – If true, the request made by a "non-instance" call will be cancelled (if not already completed) by calling $cancelRequest() on the call's return value. This can be overwritten per action. (Defaults to false.)

Returns

Object

A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

{
  'get':    {method: 'GET'},
  'save':   {method: 'POST'},
  'query':  {method: 'GET', isArray: true},
  'remove': {method: 'DELETE'},
  'delete': {method: 'DELETE'}
}

Calling these methods invoke $http with the specified http method, destination and parameters. When the data is returned from the server then the object is an instance of the resource class. The actions save, remove and delete are available on it as methods with the $ prefix. This allows you to easily perform CRUD operations (create, read, update, delete) on server-side data like this:

var User = $resource('/user/:userId', {userId: '@id'});
User.get({userId: 123}).$promise.then(function(user) {
  user.abc = true;
  user.$save();
});

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

The action methods on the class object or instance object can be invoked with the following parameters:

  • "class" actions without a body: Resource.action([parameters], [success], [error])
  • "class" actions with a body: Resource.action([parameters], postData, [success], [error])
  • instance actions: instance.$action([parameters], [success], [error])

When calling instance methods, the instance itself is used as the request body (if the action should have a body). By default, only actions using POST, PUT or PATCH have request bodies, but you can use the hasBody configuration option to specify whether an action should have a body or not (regardless of its HTTP method).

Success callback is called with (value (Object|Array), responseHeaders (Function), status (number), statusText (string)) arguments, where value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument.

Class actions return an empty instance (with the additional properties listed below). Instance actions return a promise for the operation.

The Resource instances and collections have these additional properties:

  • $promise: The promise of the original server interaction that created this instance or collection.

    On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in the resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

    On failure, the promise is rejected with the http response object.

    If an interceptor object was provided, the promise will instead be resolved with the value returned by the response interceptor (on success) or responceError interceptor (on failure).

  • $resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding. If there is a response/responseError interceptor and it returns a promise, $resolved will wait for that too.

    The Resource instances and collections have these additional methods:

  • $cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.

    The Resource instances have these additional methods:

  • toJSON: It returns a simple object without any of the extra properties added as part of the Resource API. This object can be serialized through angular.toJson safely without attaching AngularJS-specific fields. Notice that JSON.stringify (and angular.toJson) automatically use this method when serializing a Resource instance (see MDN).

Examples

Basic usage

// Define a CreditCard class
var CreditCard = $resource('/users/:userId/cards/:cardId',
  {userId: 123, cardId: '@id'}, {
    charge: {method: 'POST', params: {charge: true}}
  });

// We can retrieve a collection from the server
var cards = CreditCard.query();
    // GET: /users/123/cards
    // server returns: [{id: 456, number: '1234', name: 'Smith'}]

// Wait for the request to complete
cards.$promise.then(function() {
  var card = cards[0];

  // Each item is an instance of CreditCard
  expect(card instanceof CreditCard).toEqual(true);

  // Non-GET methods are mapped onto the instances
  card.name = 'J. Smith';
  card.$save();
      // POST: /users/123/cards/456 {id: 456, number: '1234', name: 'J. Smith'}
      // server returns: {id: 456, number: '1234', name: 'J. Smith'}

  // Our custom method is mapped as well (since it uses POST)
  card.$charge({amount: 9.99});
      // POST: /users/123/cards/456?amount=9.99&charge=true {id: 456, number: '1234', name: 'J. Smith'}
});

// We can create an instance as well
var newCard = new CreditCard({number: '0123'});
newCard.name = 'Mike Smith';

var savePromise = newCard.$save();
    // POST: /users/123/cards {number: '0123', name: 'Mike Smith'}
    // server returns: {id: 789, number: '0123', name: 'Mike Smith'}

savePromise.then(function() {
  // Once the promise is resolved, the created instance
  // is populated with the data returned by the server
  expect(newCard.id).toEqual(789);
});

The object returned from a call to $resource is a resource "class" which has one "static" method for each action in the definition.

Calling these methods invokes $http on the url template with the given HTTP method, params and headers.

Accessing the response

When the data is returned from the server then the object is an instance of the resource type and all of the non-GET methods are available with $ prefix. This allows you to easily support CRUD operations (create, read, update, delete) on server-side data.

var User = $resource('/users/:userId', {userId: '@id'});
User.get({userId: 123}).$promise.then(function(user) {
  user.abc = true;
  user.$save();
});

It's worth noting that the success callback for get, query and other methods gets called with the resource instance (populated with the data that came from the server) as well as an $http header getter function, the HTTP status code and the response status text. So one could rewrite the above example and get access to HTTP headers as follows:

var User = $resource('/users/:userId', {userId: '@id'});
User.get({userId: 123}, function(user, getResponseHeaders) {
  user.abc = true;
  user.$save(function(user, putResponseHeaders) {
    // `user` => saved `User` object
    // `putResponseHeaders` => `$http` header getter
  });
});

Creating custom actions

In this example we create a custom method on our resource to make a PUT request:

var app = angular.module('app', ['ngResource']);

// Some APIs expect a PUT request in the format URL/object/ID
// Here we are creating an 'update' method
app.factory('Notes', ['$resource', function($resource) {
  return $resource('/notes/:id', {id: '@id'}, {
    update: {method: 'PUT'}
  });
}]);

// In our controller we get the ID from the URL using `$location`
app.controller('NotesCtrl', ['$location', 'Notes', function($location, Notes) {
  // First, retrieve the corresponding `Note` object from the server
  // (Assuming a URL of the form `.../notes?id=XYZ`)
  var noteId = $location.search().id;
  var note = Notes.get({id: noteId});

  note.$promise.then(function() {
    note.content = 'Hello, world!';

    // Now call `update` to save the changes on the server
    Notes.update(note);
        // This will PUT /notes/ID with the note object as the request payload

    // Since `update` is a non-GET method, it will also be available on the instance
    // (prefixed with `$`), so we could replace the `Note.update()` call with:
    //note.$update();
  });
}]);

Cancelling requests

If an action's configuration specifies that it is cancellable, you can cancel the request related to an instance or collection (as long as it is a result of a "non-instance" call):

// ...defining the `Hotel` resource...
var Hotel = $resource('/api/hotels/:id', {id: '@id'}, {
  // Let's make the `query()` method cancellable
  query: {method: 'get', isArray: true, cancellable: true}
});

// ...somewhere in the PlanVacationController...
...
this.onDestinationChanged = function onDestinationChanged(destination) {
  // We don't care about any pending request for hotels
  // in a different destination any more
  if (this.availableHotels) {
    this.availableHotels.$cancelRequest();
  }

  // Let's query for hotels in `destination`
  // (calls: /api/hotels?location=<destination>)
  this.availableHotels = Hotel.query({location: destination});
};

Using interceptors

You can use interceptors to transform the request or response, perform additional operations, and modify the returned instance/collection. The following example, uses request and response interceptors to augment the returned instance with additional info:

var Thing = $resource('/api/things/:id', {id: '@id'}, {
  save: {
    method: 'POST',
    interceptor: {
      request: function(config) {
        // Before the request is sent out, store a timestamp on the request config
        config.requestTimestamp = Date.now();
        return config;
      },
      response: function(response) {
        // Get the instance from the response object
        var instance = response.resource;

        // Augment the instance with a custom `saveLatency` property, computed as the time
        // between sending the request and receiving the response.
        instance.saveLatency = Date.now() - response.config.requestTimestamp;

        // Return the instance
        return instance;
      }
    }
  }
});

Thing.save({foo: 'bar'}).$promise.then(function(thing) {
  console.log('That thing was saved in ' + thing.saveLatency + 'ms.');
});

© 2010–2020 Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
https://code.angularjs.org/1.8.2/docs/api/ngResource/service/$resource