[译]了解AngularJS $resource

原文: https://learnable.com/books/angularjs-novice-to-ninja/preview/understanding-angularjs-resource-e0638c0

 

多数AngularJS应用都需要一些CRUD操作. 你可以使用$resource服务快速的进行一个CRUD.

前提

$resource服务不包含在angular.js中. 因为不是每个Angular应用都需要CRUD操作, 如果你需要使用$resource服务你必须首先引用angular-resource.js文件.

然后你需要把ngResource注入到你的app中:

angular.module('myApp',  ['ngResource']);

我们这样做是因为$resource服务定义在ngResource模块中.

$resource是怎么工作的?

$resource和RESTful API工作. 这意味着你的的URLS应该类似于下面的模式

URLHTTP VerbRequest BodyResult
/api/entries GET empty Returns all entries
/api/entries POST JSON String Creates new entry
/api/entries/:id GET empty Returns single entry
/api/entries/:id PUT JSON String Updates existing entry
/api/entries/:id DELETE empty Deletes existing entry

为了在你的controller或者service中使用 $resource, 你需要声明一个对$resource的依赖. 下面的代码展示了如何在你的自定义服务中使用$resource:

angular.module('myApp').factory('Entry', fucntion($resource){
    return $resource('/api/entries/:id');
});

$resource默认有5个方法:

  1. get()

  2. query()

  3. save()

  4. remove()

  5. delete()

现在来看看怎么使用这些方法:

angular.module('myApp').controller('ResourceController',
  function($scope, Entry) {
    var entry = Entry.get({ id: $scope.id }, function() {
      console.log(entry);
    }); // get() 返回单个entry

    var entries = Entry.query(function() {
      console.log(entries);
    }); //query() 返回所有的entry

    $scope.entry = new Entry(); //你可以实例化一个resource类

    $scope.entry.data = 'some data'; // $scope.entry= {data:'some data'}

    Entry.save($scope.entry, function() {
          //把$scope.entry序列化成一个JSON作为POST body
    });

    Entry.delete({ id: $scope.id }, function() {
      console.log('Deleted from server');
    });
});

get() 函数发起了一个GET请求 /api/entries/:id.  在发送前我们把:id赋值为$scope.id. 注意了get()函数返回了一个空对象. 当数据从服务器返回的时候会自动填充到这个空对象. get()函数的第二个方法会在数据从服务器返回的时候执行. 你可以在这里把返回值赋值给$scope.

为什么使用空对象?

You might question the wisdom of showing an empty object initially. Actually it's a good thing because you can omit the callback passed toget() function. 如果你只是想把model赋值给$scope而不关心数据是什么时候从服务器返回的, 你可以使用下面的方法:

$scope.entry = Entry.get({ id: $scope.id });

如果get不返回一个空对象的话, 你需要添加一个callback:

Entry.get({id: $scope.Id}, function(entry){
    $scope.entry = entry;
);

query()对/api/entries 发起了一个get请求(注意了没有:id) 并返回一个空数组 (不是一个简单的对象). 当数据从服务器返回的时候这个空对象会被填充.

save()对 /api/entries 发起了一个post请求. 第一个参数是POST body. 第二个参数是callback, 当数据保存完成后触发. You might recall that the return value of the $resource() function is a resource class. So, in our case, we can call new Entry() to create an actual resource instance, set various properties to it and finally save the object to the back end.

delete() 和 remove() 都对/api/entries/:id发起一个delete请求

使用 remove() 兼容IE

有些IE浏览器可能不支持delete(). 可以使用remove兼容IE.

在resource类中我们只使用get() query() (在我们的例子中resource类是Entry). 所有非GET的方法, 例如 save()和 delete()在 new Entry()的实例中能用 (在这我们把它称为 $resource 实例). 不同的是这些方法以$开头

$save()
$delete()
$remove()

看看$save()方法是怎么使用的:

$scope.entry = new Entry();//这个对象有个$save()方法
$scope.entry.$save(function(){
    console.log('data saved');
}); // $scope.entry 序列化成JSON作为POST body被发送

为了支持update操作, 我们需要修改代码如下

angular.module('myApp').factory('Entry', function($resource){
    return $resource('/api/entries/:id', {id:'@_id'},{
        update: {
          method: 'PUT'
        } 
    });
});

$resource()的第二个指示url的:id参数的值应该是什么. 这里设置为@_id, 当你调用$resource实例的$delete()和$update()的时候, :id的值会被设置为实例的_id属性. 这个是为PUT和DELETE请求使用的. 注意第三个参数. 这是一个map允许我们给resource类添加自定义的方法. 如果方法不是一个get请求的话, $resource实例会有一个以$开头的同名方法. 现在看看怎么使用$update方法:

$scope.entry = Entry.get({id:$scope.id}, function(){
    //$scope.entry 是服务器返回来的 是一个Entry的实例
    $scope.entry.data = 'something else';
    $scope.entry.$update(function(){
        console.info('updated');
    });
});

当$update被调用, 会发生下面的东西:

  1. AngularJS 知道$update()会触发一个对/api/entries/:id的PUT请求.

  2. 读取$scope.entry._id并将赋值给url的:id参数.

  3. 将$scope.entry作为一个请求体PUT个URL.

同样, 如果你想删除一个entry你可以这样做:

$scope.entry = Movie.get({id: $scope.id}, function(){
    $scope.entry.$delete(function(){
        //completed
    });
});

使用 MongoDB

如果你使用的是MongoDB, 你从后端获取到的$scope.entry实例通常有一个叫_id的属性. { id: '@_id' } 当调用$update()或者$delete()的时候, url的:id参数会被赋值为实例的_id属性 .

 

$resource第四个参数是可选的. 它是一个客户自定义的配置. 这里我们只设置 stripTrailingSlashes. 默认情况下它的值是true, 这意味他会自动去除url的最后一个/. 如果你不想这样可以这样:

angular.module('myApp').factory('Entry', function($resource) {
  return $resource('/api/entries/:id', { id: '@_id' }, {
    update: {
      method: 'PUT' // this method issues a PUT request
    }
  }, {
    stripTrailingSlashes: false
  });
});

  

posted @ 2015-04-30 10:27  irocker  阅读(7625)  评论(0编辑  收藏  举报