REST (representational status transfer, representational state Transfer) is a software architecture style proposed by Dr. Roy Fielding in his doctoral dissertation in 2000. RESTful style design is not only more readable (Human readable), but also easy to do cache and server Extensions (scalability). The rest style is reflected in the URL design:
- Each URL corresponds to a resource
- Different actions for resources correspond to HTTP methods
- Resource representation (representation) Adoption
Accept
and Content-Type
designation
ANGULARJS provides a service to make it easier to $resource
interact with the RESTful server API, and it is easy to define a rest resource without having to manually declare all the CRUD methods.
Reference Document: https://docs.angularjs.org/api/ngResource/service/$resource
Resource Factory
$resource
Service definition in ngResource
module, you need to introduce this module in your HTML JS, while adding such a dependency in your app:
var app = angular.module(‘helloApp, [‘ngResource‘]);
Then create a factory for the resource:
app.factory(‘Notes‘, [‘$resource‘, function($resource) { return $resource(‘/notes/:id‘);}]);
Of course, you can also not put $esource
the instance into the factory, directly in the controller stored up: var Notes = $resource(‘/notes/:id)
.
Crud
In your controller you can add and remove resources to check:
App.Controller(' Notesctrl ',[' $scope ',' Notes ',function($scope,Notes){VarNotes=Notes.Query(function(){GET:/notesResponse: [{id:1, content: ' Hello '}, {id:2, Content: ' World '};VarFirst=Notes[0];First.Content=' Halo ';first. $save(); //update effects //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 effect //POST:/notes //Response: {id:3, content: ' xxx '}}]);
PUT operation
$resource
provides five default actions: get
, query
, save
, remove
, Delete
. You can configure an update
operation to complete the HTTP PUT:
app.factory(‘Notes‘, [‘$resource‘, function($resource) { return $resource(‘/notes/:id‘, null, { update: { method:‘PUT‘ } }); }]);
Now you can get a note in the controller and update it:
var note = notes. Get ({id: 3}), $id = note. Id; Note. Content = ' yyy ' ; Notes. Update ({id: $id }, note); //PUT/NOTES/3 {id:3, content: ' yyy '}
Now you Notes
have six kinds of operation. These operations are called in two ways:
- Called through a resource class, for example:
Notes.update({id: xxx})
;
- Called through the resource instance, for example:
note.$update()
, at which point the operation name needs to be prefixed $
.
The specific invocation parameters refer to the documentation:
HTTP get "Class" Actions:Resource.action ([parameters], [success], [ERROR]) Get resource class call
Non-get "Class" Actions:Resource.action ([parameters], PostData, [success], [ERROR]) non-GET (update,post,delete) resource class calls
Non-get instance actions:instance. $action ([parameters], [success], [ERROR]) non-GET resource instance calls
Where the success parameter is (value, responseHeaders)
, the error parameter is (httpResponse)
.
Attribute/url mappings
In the example above, we see that the attributes of the note object id
are mapped to the () in the URL :id
/notes/:id
. If your business is more complex, you can configure this mapping relationship manually. For example:
var Notes = $resouce(‘/users/:userId/notes/:noteId‘, { noteId: ‘@id‘, userId: ‘@owner‘}
Will read note
the owner
and id
properties to generate the URL, such as when deleting the note:
// note === {id: 123, owner: ‘alice‘, content: ‘hello‘}note.$delete();// DELETE: /users/alice/notes/123
At construction $resource
time, more than a property map becomes a URL Query. For example:
var Notes = $resouce(‘/notes/:id‘, { id: ‘@id‘, user: ‘@owner‘});// note === {id: 123, owner: ‘alice‘, content: ‘hello‘}note.$delete();// DELETE: /notes/123?user=alice
More than one property in the declaration and invocation of a rest operation becomes a URL Query. For example:
VarNotes=$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 '}
Response conversions
Sometimes a fully restful API cannot be provided based on a given background design, such as /notes
a pager object, not an array. At this point, we can still use it $resource
, but we need to set the response conversion callback. For example:
VarNotes=$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 (datareturn pager. Content} }}); var notes = notes. Query (function () {//GET:/notes //notes = = = [{id:1, content: ' Hello '}, {id:2, Content: ' World '}]
Similar to the response rewrite, you can also set the request transformation transformRequest
.
While $resource
the design can support the vast majority of URLs and content presentation designs, if you find $resource
the use process extremely complex, it may be that your server API does not satisfy the restful style.
Unless noted, this blog article is original, reproduced please link to the form of this article address: http://harttle.com/2015/06/05/angular-resource.html
The correspondence between AngularJS $resource and backstage Restapi