- service in module ngResource
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
$http
$log
$q
$timeout
Usage
$resource(url, [paramDefaults], [actions], options);
Arguments
Param | Type | Details |
---|---|---|
url | string | A parameterized URL template with parameters prefixed by If you are using a url with a suffix, just add the suffix, like this: |
paramDefaults (optional) | Object | Default values for 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 If the parameter value is prefixed with |
actions (optional) | Object.<Object>= | Hash with declaration of custom actions that should extend the default set of resource actions. The declaration should be created in the format of $http.config: {action1: {method:?, params:?, isArray:?, headers:?, ...}, action2: {method:?, params:?, isArray:?, headers:?, ...}, ...} Where:
|
options | Object | Hash with custom settings that should extend the default
|
Returns
Object |
A resource "class" object with methods for the default set of resource actions optionally extended with custom { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; Calling these methods invoke an var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { 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 The action methods on the class object or instance object can be invoked with the following parameters:
Success callback is called with (value, responseHeaders) arguments, where the value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument. Class actions return empty instance (with additional properties below). Instance actions return promise of the action. The Resource instances and collections have these additional properties:
|
Credit card resource
// Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(function() { // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/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"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'0123', name: 'Mike Smith'}; expect(newCard.id).toEqual(789);
The object returned from this function execution is a resource "class" which has "static" method for each action in the definition.
Calling these methods invoke $http
on the url
template with the given method
, params
and headers
.
User resource
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('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(user) { user.abc = true; user.$save(); });
It's worth noting that the success callback for get
, query
and other methods gets passed in the response that came from the server as well as $http header getter function, so one could rewrite the above example and get access to http headers as:
var User = $resource('/user/: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 }); });
You can also access the raw $http
promise via the $promise
property on the object returned
var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}) .$promise.then(function(user) { $scope.user = user; });
Creating a custom 'PUT' request
In this example we create a custom method on our resource to make a PUT request
var app = angular.module('app', ['ngResource', 'ngRoute']); // 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', null, { 'update': { method:'PUT' } }); }]); // In our controller we get the ID from the URL using ngRoute and $routeParams // We pass in $routeParams and our Notes factory along with $scope app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', function($scope, $routeParams, Notes) { // First get a note object from the factory var note = Notes.get({ id:$routeParams.id }); $id = note.id; // Now call update passing in the ID first then the object you are updating Notes.update({ id:$id }, note); // This will PUT /notes/ID with the note object in the request payload }]);
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/hotel/: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 this.availableHotels.$cancelRequest(); // Let's query for hotels in '<destination>' // (calls: /api/hotel?location=<destination>) this.availableHotels = Hotel.query({location: destination}); };
Please login to continue.