如果只是用來作CRUD的AJAX, $resource會是一個比較好的選擇.
參考書: Novice to Ninja, Understanding AngularJS $resource, page-171
1. 使用前的準備
因為不是每一個app都需要CRUD功能,所以$resource並不包含在標準的angularJS中.
要使用它必需另外載入angularjs-resources.js, 並將"ngResource"加入module的相依性中.
angular.module('myApp',['ngResource']);
2. 概述
$resource本身就已經是一個factory物件,所以在呼叫它後會返回物件並包含一些methods.
原型: $resource(URL, paramDefaults, actions)
URL: string
paramDefaults: optional object. 可設定參數的初始值或mapping
- 初始值: {id: "123"}
- mapping: {id: "@_id"}, 就是加上一個前置符號
actions: optional object, 可自行擴充(之後有提到).
舉例來說:
用法1
var User = $resource('/api/users/:id');
用法2
var User = $resource('/api/users/:id',{ id: '@_id' }
,{update:
{
method: 'PUT' // this method issues a PUT request
}
});
User就可以拿來做CRUD. 它包含以下的methods 1. get() 2. query() 3. save() 4. remove() : 因為IE下,delete()會發生問題,所以需使用remove() 5. delete() 3. get : 取一筆資料 原型: get(params, successFn, errorFn) // Issues a request to:// GET /api/users/123 User.get({id: '123'}, function(resp) { // Handle successful response here }, function(err) { // Handle error here }); 會送出 /api/users/123 的resource到server端. resp為傳回的資料. Note: get的第1個參數的傳入的物件的資料的名稱要與取得resource時傳入的URL的名稱相同. 例如$resource('/api/users/:id'), 那get傳入要寫成get({id: '123'}),那123就會直接取代:id的位置 4. query : 取全部的資料 原型:query(params, successFn, errorFn) // Issues a request to:// GET /api/users User.query(function(users) { // The first user in the collection var user = users[0]; }); 5. save() : 建立一筆資料 原型: save(params, payload, successFn, errorFn) // Issues a request to:// POST /api/users // with the body {name: 'Ari' } User.save({}, { name: 'Ari' }, function(response) { // Handle a successful response }, function(response) { // Handle a non-successful response }); 6. delete/remove : 刪除一筆資料 // Issues a request to:// DELETE /api/users User.remove({}, { id: '123' }, function(response) { // Handle a successful remove response }, function(response) { // Handle a non-successful remove response }); 7. 利用$resource 回傳的instance作update 首先在取得$resource時,使用上面提過的方法2. 其第2個參數是一個mapping,將URL中的id參 數在呼叫$update或$delete時會將它mapping到_id (因為server端定義的欄位名是_id). 而第3個參數則是新增了一個$update的method,而且會使用PUT作為協定. (PUT在REST是指更新) 以下為更新一筆資料的的某個欄位. 在使用get取回資料後,回傳的實體中有提供$save/$delete/$query/$remove/$update(這是自定義的). 將該筆資料的name改為Ari後,呼叫$update更新資料. 從網路封包的資料分析,會傳送整個user的資料 到server端,且name='Ari'將資料更新. // Using the $save() instance methods User.get({id: '123'}, function(user) { user.name = 'Ari'; user.$update(); // update the user }); 如果Server端有支援新增功能,以下的用法與上面的功用相同 // This is equivalent to the collection-level // resource call User.save({id: '123'}, {name: 'Ari'}); 還有另一些擴充的方式: var User = $resource('/api/users/:userId.json', {userId: '@id'}, { sendEmail: {method: 'POST'}, allInboxes: { method: 'JSONP', isArray: true } }); 像上述的update也是用擴充的方式. 擴充完成後,直接可以使用如User.update(), User.sendEmail()等. 8. $resource的$promise(promise)與$resolve(boolen) 尚未了解要如何應用. 9. $resource的transformRequest與transformResponse 在逃resource中一樣可以使用與$http相同的transformRequest與transformResponse方法 var User = $resource('/api/users/:id', { id: '@' }, { sendEmail: { method: 'PUT', transformRequest: function(data, headerFn) { // Return modified data for the request return JSON.stringify(data); } } }); var User = $resource('/api/users/:id', { id: '@' }, { sendEmail: { method: 'PUT', transformResponse: function(data, headerFn) // Return modified data for the response return JSON.parse(data); } } }); 10. 其他參數 (參考ng-bool $resource Configuration Object, page192) - cache (boolean) - timeout (number/promise) - withCredential(boolen) - responseType(string) ‧ ”” (string – default) ‧ “arraybuffer” (ArrayBuffer) ‧ “blob” (blob object) ‧ “document” (HTTP document) ‧ “json” (JSON object parsed from a JSON string) ‧ “text” (string) ‧ “moz-blob” (Firefox to receive progress events) ‧ “moz-chunked-text” (streaming text) ‧ “moz-chunked-arraybuffer” (streaming ArrayBuffer) - interceptor(object) ==================================== 其他參考資源/測試 1. Creating a CRUD App in Minutes with Angular’s $resource(http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/) 有提供測試的RESTful : Get All movies: http://movieapp-sitepointdemos.rhcloud.com/api/movies Get 1 movie: http://movieapp-sitepointdemos.rhcloud.com/api/movies/3031 ==================================== 其他參考書目 1. NG-Book: page157, Services
沒有留言:
張貼留言