angularJS $resource与后台restapi的对应关系

REST(表征性状态传输,Representational State Transfer)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。RESTful风格的设计不只具备更好的可读性(Human Readable),并且易于作缓存以及服务器扩展(scalability)。REST风格体如今URL设计上:javascript

  • 每一个URL对应一个资源
  • 对资源的不一样操做对应于HTTP的不一样方法
  • 资源表现形式(representation)经过AcceptContent-Type指定

AngularJS提供了$resourceService来更方便地与RESTful服务器API进行交互,能够方便地定义一个REST资源,而没必要手动全部的声明CRUD方法。html

参考文档: https://docs.angularjs.org/api/ngResource/service/$resourcejava

Resource Factory

$resourceService定义在ngResourceModule中,须要在你的HTML中引入这个Module对应的JS,同时在你的APP中添加这样一个依赖:angularjs

var app = angular.module('helloApp, ['ngResource']); 

而后为资源创建一个Factory:api

app.factory('Notes', ['$resource', function($resource) { return $resource('/notes/:id'); }]); 

固然,你也能够不把$esource的实例放到Factory里,直接在控制器中存起来:var Notes = $resource('/notes/:id)数组

CRUD

在你的控制器中就能够对资源进行增删改查了:缓存

app.controller('NotesCtrl', ['$scope', 'Notes', function($scope, Notes) { var notes = Notes.query(function(){ // GET: /notes // Response: [{id: 1, content: 'hello'}, {id: 2, content: 'world'}]; var first = notes[0]; first.content = 'halo'; first.$save(); //update效果 // POST: /notes/1 {id: 1, content: 'halo'} // Response: {id: 1, content: 'halo'} second.$delete(); // DELETE: /notes/2 }); var note = new Notes({content: 'xxx'}); note.$save(); // insert效果 // POST: /notes // Response: {id: 3, content: 'xxx'} }]); 

PUT 操做

$resource提供了五种默认操做:getquerysaveremovedelete。你能够配置一个update操做来完成HTTP PUT:服务器

app.factory('Notes', ['$resource', function($resource) { return $resource('/notes/:id', null, { update: { method:'PUT' } }); }]); 

如今,你能够在控制器中获取一个note并更新它:架构

var note = Notes.get({ id: 3}), $id = note.id; note.content = 'yyy'; Notes.update({ id:$id }, note); // PUT /notes/3 {id: 3, content: 'yyy'} 

如今你的Notes有六种操做了。这些操做有两种调用方式:app

  1. 经过资源类调用,例如:Notes.update({id: xxx})
  2. 经过资源实例调用,例如:note.$update(),此时操做名需加前缀$

具体的调用参数可参考文档:

HTTP GET "class" actions: Resource.action([parameters], [success], [error])     get资源类调用

non-GET "class" actions: Resource.action([parameters], postData, [success], [error])   非get(update,post,delete)资源类调用

non-GET instance actions: instance.$action([parameters], [success], [error])    非get资源实例调用

其中,success参数为(value, responseHeaders),error参数为(httpResponse)

属性/URL映射

上述例子中,咱们看到note对象的id属性会映射到URL中的:id/notes/:id)。若是你的业务更加复杂,能够手动配置这个映射关系。例如:

var Notes = $resouce('/users/:userId/notes/:noteId', { noteId: '@id', userId: '@owner' } 

将会读取noteownerid属性来生成URL,好比删除note时:

// note === {id: 123, owner: 'alice', content: 'hello'} note.$delete(); // DELETE: /users/alice/notes/123 

在构造$resource时,多于的属性映射会成为URL Query。例如:

var Notes = $resouce('/notes/:id', { id: '@id', user: '@owner' }); // note === {id: 123, owner: 'alice', content: 'hello'} note.$delete(); // DELETE: /notes/123?user=alice 

REST操做的声明和调用中,多于的属性会成为URL Query。例如:

var Notes = $resouce('/notes/:id', {id: '@id'}, { update: {method: 'PUT', operator: 'bob'} }); // note === {id: 123, content: 'hello'} note.$update({trusted: true}); // PUT: /notes/123?operator=bob&trusted=true {id: 123, content: 'hello'} 

响应转换

有时基于既定的后台设计,没法提供彻底RESTful的API,好比/notes返回的是一个分页器对象,而非数组。此时,咱们仍然可使用$resource,但须要设置响应转换回调。例如:

var Notes = $resouce('/notes/:id', null, { pager: { method: 'GET', transformResponse: function(data, headers){ // Server respond: // data = {currentPage: 1, // totalPage: 20, // pageSize: 2, // content: [{id: 1, content: 'hello'}, {id: 2, content: 'world'}]} var pager = JSON.parse(data); return pager.content; } } }); var notes = Notes.query(function(){ // GET: /notes // notes === [{id: 1, content: 'hello'}, {id: 2, content: 'world'}] }); 

相似响应重写,你还能够设置请求转换transformRequest

虽然$resource的设计能够支持绝大多数的URL和内容表示设计,但若是你发现$resource的使用过程极其复杂,那多是你的服务器API并不知足RESTful风格。

相关文章
相关标签/搜索