您的位置:首页 > Web前端 > AngularJS

Angular之$resource

2016-03-16 11:17 477 查看

什么是$resource

它是创建资源对象的工厂,底层封装了$http service,提供与RESTful服务端数据资源进行交互。

Usage

默认情况下,末尾斜杠(可以引起后端服务器不期望出现的行为)将从计算后的URL中剥离。

这个可以通过$resourceProvider配置:

app.config(["$resourceProvider",function($resourceProvider){

$resourceProvider.defaults.stripTrailingSlashes = false;

}]);


使用规范

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


url

参数需加前缀为‘:‘,e.g. /user/:username

可以加port,e.g. http://example.com:8080/api

可以使用后缀 , e.g.
$resource('http://example.com/resource.json')
$resource('http://example.com/:id.json')
甚至
$resource('http://example.com/resource/:resource_id.:format')
如果在/后直接加’.’会默认跳过,可以加’
/\.


paramDefaults(可选,object类型)

url参数中的默认值。可在action方法中被覆盖。

若任一参数为函数,则每当一次请求需要获取参数值时,都将被执行(除非参数被覆盖)。

参数对象中的每个键值对,若在url模板中存在则会被首先绑定,多余的键将被添加到url搜索查询(?之后)。e.g.给定模板/path/:verb与参数{verb:’greet’,salutation:’Hello’},将得到URL/path/greet?salutation=Hello。

若参数值以’@’作为前缀,则当调用action方法时该参数的值将被从对应data对象中取出e.g. {someParam: ‘@someProp’},someParam的值从data.someProp取出

actions

声明扩展默认资源动作集合的自定义动作的声明集合。声明应以$http.config的格式创建

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


action - {string} - :动作名。该名称成为你的资源对象的方法名。

method – {string} – :HTTP请求方法。合法的方法包括GET, POST, PUT, DELETE和JSONP。

params – {Object=} –: 该动作提前绑定的参数的可选集合。若任一参数为函数,则每当一次请求需要获取参数值时,都将被执行(除非参数被覆盖)。

url – {string} – :动作特定url覆盖。支持url模板,与资源级别url相似。

isArray – {boolean=} – :若为true,返回对象是一个数组。

transformRequest-{function(data,headersGetter)|Array.<function(data, headersGetter)>}
:一个转换函数或者一个包含多个转换函数的数组。转换函数获取http请求体和请求头,并且返回他们的转换版(通常是序列化)。request data是一个object对象,则用angular.toJson序列化它,防止该行为可设为transformRequest: []。

transformResponse – {function(data, headersGetter)|A
4000
rray.<function(data, headersGetter)>}
:转换函数或者一个包含多个转换函数的数组。转换函数获取http响应体和响应头,并且返回他们的转换版(通常是序列化)。若response是一个Json string则用angular.fromJson反序列化它,防止该行为可设transformResponse: []

cache – {boolean|Cache} –:如果为true,一个默认的
$http
缓存将被使用去缓存GET request,否则用$cacheFactory创建的缓存实例,将用于缓存。

timeout – {number|Promise}–:用于毫秒或promise超时让请求中止。

withCredentials - {boolean} -:是否设置withcredentials flag的XHR对象。需要更多信息查API。

responseType - 响应头类型,需要更多信息查API。

interceptor - {Object=} -:对象,拦截对象有两个可选方法-response和responseError,需要更多信息查API。

option

扩展$resourceProvider行为的自定义设置,唯一支持的选项是stripTrailingSlashes,boolean类型,如果为真,url尾部的斜杠会被移除(默认为true)。

return

返回一个资源“类”对象。该对象包含默认资源动作的方法,和可选的自定义的扩展动作。默认集合包含以下动作:

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


调用这些方法以特定的http方法、目标和参数调用
$http
。数据从服务器返回后,该对象将是该资源类的一个实例。save,remove,delete动作($前缀)可作为该对象的方法使用。这允许你很容易地对服务器端数据进行CRUD操作,如:

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


调用$resource对象的方法将立即返回一个空引用(对象或数组依isArray而定)。数据一旦从服务器返回,该引用将填充具体的数据。这是 一个有用的技巧,因为资源通常被赋给一个模型,模型随即被视图渲染。一个空对象不会被渲染,而当数据从服务器返回,那么该对象将填充数据,视图会自动重新 渲染、以显示新的数据。这意味着在多数情况下没有必要为动作方法写回调函数。

类对象或实例对象中的动作方法可以用以下参数进行调用:

HTTP GET “类”动作: Resource.action([parameters], [success], [error])

non-GET “类”动作: Resource.action([parameters], postData, [success],

[error])

non-GET 实例动作: instance.$action([parameters], [success], [error])

Success回调以(value, responseHeaders)参数调用。Error回调以(httpResponse)参数回调。

class 动作返回空的实例,而实例动作返回这动作的promise。

$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 resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

On failure, the promise is resolved with the http response object, without the resource property.

If an interceptor object was provided, the promise will instead be resolved with the value returned by the interceptor.

$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.

Example

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);


这个执行函数返回“类”资源对象,该对象有定义静态的遍历方法,这些方法会调用
$http
在url中的
method, params and headers
,当从服务器获得data后,该对象就变成一个实例,所有的non-GET methods(前缀$)就变得可用,这就可以便捷的进行CRUD。

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


值得注意的是,这个success回调可以像$http header getter 方法那样使用, 所以重写上例子:

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


你也可以在返回的对象上使用
$promise


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


Creating a custom ‘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' }
});
}]);


参考文档

http://docs.angularjs.cn/api/ngResource/service/$resource

http://www.ithao123.cn/content-5602494.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: