$resource是angular自带的一个服务,这个服务会创建一个用来和restful风格的服务端数据进行交互的一个对象(a resource object),通过这个对象来完成CURD操作。
使用服务时需要先在页面上引入ngResource模块,$resource服务依赖于$http服务,
使用:
$resource(url, [paramDefaults], [actions]);
参数说明:
- url(string)
字符串类型,是一个参数化的URL模板,URL中的参数以:为前缀,例如:/user/:id(:id在具体请求中被替换成具体的参数值)
- paramDefaults(object)
URL模板中指定参数的默认值,这些值在具体请求方法中可以被重写,如果这些参数值中有函数,当URL模板得到具体的请求参数时函数就会被执行。
此对象中与URL模板中相对应的参数值在使用时会替换模板中的参数,剩下的参数及值被添加到URL的?后面
例如:URL Template: /path/:vert
parameter: {vert:'greet',salutation: 'hello'}
实际的URL请求为:/path/greet?salutation=hello
如果对象中的某个参数值是以@开头的字符串,那么此参数值将会被数据对象中相应的参数值代替
例如:var User=$resource('/user/:id',{"id":"@id"}); User.get({'id':'123'});则实际的请求URL为/user/123。
- actions
此选项用来声明自定义请求类型,声明被创建在$http.config
例子:
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' }
});
}]); //返回的resource对象就有update请求方法
// 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
}]);
返回的resource'类'
$resource对象创建的resource'类'默认包含以下请求方法:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
调用这些方法会执行带有特定http方法,路径和参数的$http。调用这些方法返回数据后,这个数据就是一个resource“类”的实例。这个实例就可以以$为前缀调用save(),remove()和delete()方法了。例如:
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
很好的例子:
// 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() { //cards即为一个resource对象集合
// 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);
我们也可以使用new操作符来生成一个resource类的实例,从而调用$save() $delete()等方法
myModule.factory('Test',[function(){ return $resource('rest/user/:userId',{'userId':'@id'}); }]) myModule.controller('TestCtrl',['Test',function(Test){ var test=new Test(); test.$save(); //等同于 Test.save() //差别在于,$save()接受三个参数,需要传递的数据要作为test对象的属性来定义 //test.testProperty='XXX' //save()接受四个参数,第一个参数为要传递的数据 }])