[譯]了解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應該類似於下面的模式

URL HTTP Verb Request Body Result
/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
  });
});

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM