[AngularJS] $resource service in AngularJS Data Modeling Series:
The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.
也就是说当用用$resource所取得的返回值是个对象,这个对象可以调用在$resource 已经封装好了的functions. 这些functions底层实质上时$http。
functions包括:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
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;
}]);
Usage
$resource(url, [paramDefaults], [actions], options);
[actions],是一个Hash collections,
Hash with declaration of custom action 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:?, ...},
...}
Example:
var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({id:123}, function() { user.abc = true; user.$save(); });
Example2:
// 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);
Read More: https://docs.angularjs.org/api/ngResource/service/$resource

浙公网安备 33010602011771号