#ngResource的理解和补充

来源:互联网 发布:软件卖图片 编辑:程序博客网 时间:2024/06/05 09:06

一.provider:$resourceProvider

作用:用来改变$resource服务的默认行为
属性:
1.stripTrailingSlashes – {boolean}:如果为真,url尾部的斜杠会被移除(默认为true)。
2.cancellable – {boolean}:
3.actions - {Object. < Object >}:
默认:

{
get: {method: ‘GET’},
save: {method: ‘POST’},
query: {method: ‘GET’, isArray: true},
remove: {method: ‘DELETE’},
delete: {method: ‘DELETE’}
}

可以更改:

angular.module(‘myApp’).config([‘$resourceProvider’, function ($resourceProvider) {
  $resourceProvider.defaults.actions = {
      create: {method: ‘POST’},
       get: {method: ‘GET’},
      getAll: {method: ‘GET’, isArray:true},
       update: {method: ‘PUT’},
      delete: {method: ‘DELETE’}
  };
});

二.service:$resource:

作用:创建一个resource对象的工厂函数,可以让你安全的和RESFUL服务端进行数据交互。需要注入 ngResource 模块。
依赖:$http、$log、$q、$timeout

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

实例:

$resource(this.listUrl).get({id: id})

url: eg:/user/:userId。(注:1.带端口号的URL(如:http://example.com:8080/api)),则需要慎重考虑。2.如果带有后缀(如:http://example.com/resource.json 或者 http://example.com/:id.json 或者 http://example.com/resource/:resource_id.:format)。如果后缀之前的参数是空的,在这情况下:resource_id 比 /.优先执行,如果你需要这个序列出现而不崩溃,那么你可以通过/.避免。

paramDefaults:url参数的默认值,这些可以在方法重写。

actions: 用户对于resource行为的默认设置进行扩展的自定义配置的散列,该配置将会以$http.config的格式创建。

实例:

$resource(“/url/_url”, {}, {
   myPost: {
    method: “post”,
    url: “/newUrl/_newUrl”,
    params: { id: “4” },
    interceptor: {
       response: function (d) {
          console.log(d);
       },
       responseError: function (d) {
          console.log(d);//这里的是随便写的地址,所以执行了error里的函数,可打印看参数及结果
       }
    }
  }
})

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

*$resource服务所返回娿对象中所包含的5个与服务端交互常用API:

1、$resource服务返回对象中的GET类型请求包含两个api,分别为get query:
两个api的请求参数相同,区别在于,get返回值可以是单个资源,但是query必须返回一个数组或集合类的资源。

var obj=$resource(‘url’);
//get()方法
obj.get(params,successFn,errorFn);
//query方法
obj.query(params,successFn,errorFn);

2、$resource服务返回对象中的非GET类型请求:
包含3个api,分别为save delete remove,其中,delete方法和remove方法作用享用,区别在于remove可以解决IE浏览器中delete是Javascript保留字而导致的错误问题
资源的方法还有一个特性: 在请求完成后,会自动用返回值来填充调用方法的资源,继而更新视图.无需在回调手动处理:
3、可以通过$resource()第三个参数来给资源自定义方法:

action: 字符串,action的名称,这个名称将成为resource对象方法的名称。

method:字符串,http方法(不区分大小写,如GET, POST, PUT, DELETE, JSONP等)。

params:对象,这次行动预先设定的参数。如果任何参数的值是一个函数,当一个参数值每一次需要获得请求时都会被执行(除非该参数被忽略的)。

url:字符串,行为指定的网址。

isArray:boolean,如果为true,那么这个行为返回的对象是个数组。

transformRequest:函数/函数的数组。转换函数或者一个包含转换函数的数组。转换函数获取http请求体和请求头,并且返回他们的转换版(通常是序列化)。

transformResponse:函数/函数的数组。转换函数或者一个包含转换函数的数组。转换函数获取http响应体和响应头,并且返回他们的转换版(通常是序列化)。

cache:boolean,如果为true,一个默认的$http缓存将被作为请求的缓存,否则如果存在一个用$cacheFactory创建的缓存实例,则将用于缓存。

timeout:数值,毫秒,超时则让请求中止。

withCredentials:boolean,是否设置withcredentials flag的XHR对象。查看更多信息的凭据。

responseType:字符串,响应头类型。

interceptor:对象,拦截对象有两个可选方法-response和responseError。

详见:流浪猫の窝的博客
使用:

$resource(‘/card/user/:userID/:id’,{userID:123,id:’@id’},{charge{method:’POST’,params:{charge:true},isArray:false}})

实例:

this.update = function (id, model) {
      return $resource(this.listUrl, {id: id}, {
      ‘update’: {method: ‘PUT’}
       }).update({id: id}, model);
};

注:会被添加$save(), $remove(), $delete三个方法,可以直接调用这三个方法来后服务端进行交互。

User.get({id:’123’}, function(user){
    user.name = ‘changeAnotherName’;
    user.$save();
    //这里等价于User.save({id:’123’},{name:’changeAnotherName’})
});

实例:

var module = angular.module( ‘my.resource’, [ ‘ngResource’ ] );
module.factory( ‘Resource’, [ ‘$resource’, function( $resource ) {
return function( url, params, methods ) {
var defaults = {
update: { method: ‘put’, isArray: false },
create: { method: ‘post’ }
};
methods = angular.extend( defaults, methods );
var resource = $resource( url, params, methods );
resource.prototype.$save = function() {
if ( !this.id ) {
return this.$create();
}
else {
return this.$update();
}
};
return resource;
};
}]);

使用:

var module = angular.module( ‘services’, [ ‘my.resource’ ] );

module.factory( ‘User’, [ ‘Resource’, function($resource ) {
return $resource( ‘users/:id’, { id: ‘@id’ } );
}]);

其中@id,{id:’@id’},表示url中的:id 将会使用资源的id属性值,也就是User的id属性值.”,对于非get类的操作是正确的,但是对于get来说就不对了。API文档中写的是@只会用于非get类的操作

resource实例和数组拥有的属性:
$promise 、$resolved、$cancelRequest、toJSON

参考文献:
[1] http://www.cnblogs.com/wshsdlau/p/5994674.html
[2] https://www.cnblogs.com/liulangmao/p/3907032.html

阅读全文
0 0
原创粉丝点击