Improve this Doc View Source $resource
- $resourceProvider
- 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 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 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. 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 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 The action methods on the class object or instance object can be invoked with the following parameters:
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 Success callback is called with (value (Object|Array), responseHeaders (Function), status (number), statusText (string)) arguments, where 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:
|
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–2018 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://code.angularjs.org/1.7.8/docs/api/ngResource/service/$resource