©
이 문서에서는PHP 중국어 웹사이트 매뉴얼풀어 주다
A factory which creates a resource object that lets you interact with RESTful server-side data sources.
The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.
Requires thengResourcemodule to be installed.
默认情况下, trailing slashes will be stripped from the calculated URLs, which can pose problems with server backends that do not expect that behavior. This can be disabled by configuring the$resourceProviderlike this:
app.config(['$resourceProvider',Function($resourceProvider){// Don't strip trailing slashes from calculated URLs$resourceProvider.defaults.stripTrailingSlashes=false;}]);
$http$resource(url,[paramDefaults],[actions],options);
| 参数 | 类型 | 详述 |
|---|---|---|
| url | string | A parametrized URL template with parameters prefixed by If you are using a url with a suffix, just add the suffix, like this: |
| paramDefaults
(可选)
|
Object | Default values for Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the Given a template If the parameter value is prefixed with |
| actions
(可选)
|
Object. | Hash with declaration of custom action that should extend the default set of resource actions. The declaration should be created in the format of $http.config: Where:
|
| options | Object | Hash with custom settings that should extend the default Where:
|
| Object | A resource "class" object with methods for the default set of resource actions optionally extended with custom Calling these methods invoke an It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on The action methods on the class object or instance object can be invoked with the following parameters:
|
// Define CreditCard classvarCreditCard=$resource('/user/:userId/card/:cardId',{userId:123,cardId:'@id'},{charge:{method:'POST',params:{charge:true}}});// We can retrieve a collection from the servervarcards=CreditCard.query(Function(){// GET: /user/123/card// server returns: [ {id:456, number:'1234', name:'Smith'} ];varcard=cards[0];// each item is an instance of CreditCardexpect(card instanceofCreditCard).toEqual(true);card.name="J. Smith";// non GET methods are mapped onto the instancescard.$save();// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}// server returns: {id:456, number:'1234', name: 'J. Smith'};// our custom method is mapped as well.card.$charge({amount:9.99});// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}});// we can create an instance as wellvarnewCard=newCreditCard({number:'0123'});newCard.name="Mike Smith";newCard.$save();// POST: /user/123/card {number:'0123', name:'Mike Smith'}// server returns: {id:789, number:'0123', name: 'Mike Smith'};expect(newCard.id).toEqual(789);
The object returned from this function execution is a resource "class" which has "static" method for each action in the definition.
Calling these methods invoke$httpon theurltemplate with the givenmethod,paramsandheaders. When the data is returned from the server then the object is an instance of the resource type and all of the non-GET methods are available with$prefix. This allows you to easily support CRUD operations (create, read, update, delete) on server-side data.
varUser=$resource('/user/:userId',{userId:'@id'});User.get({userId:123},Function(user){user.abc=true;user.$save();});
It's worth noting that the success callback forget,queryand other methods gets passed in the response that came from the server as well as $http header getter function, so one could rewrite the above example and get access to http headers as:
varUser=$resource('/user/:userId',{userId:'@id'});User.get({userId:123},Function(u,getResponseHeaders){u.abc=true;u.$save(Function(u,putResponseHeaders){//u => saved user object//putResponseHeaders => $http header getter});});
You can also access the raw$httppromise via the$promiseproperty on the object returned
varUser=$resource('/user/:userId',{userId:'@id'});User.get({userId:123}).$promise.then(Function(user){$scope.user=user;});
In this example we create a custom method on our resource to make a PUT request
varapp=angular.module('app',['ngResource','ngRoute']);// Some APIs expect a PUT request in the format URL/object/ID// Here we are creating an 'update' methodapp.factory('Notes',['$resource',Function($resource){return$resource('/notes/:id',null,{'update':{method:'PUT'}});}]);// In our controller we get the ID from the URL using ngRoute and $routeParams// We pass in $routeParams and our Notes factory along with $scopeapp.controller('NotesCtrl',['$scope','$routeParams','Notes',Function($scope,$routeParams,Notes){// First get a note object from the factoryvarnote=Notes.get({id:$routeParams.id});$id=note.id;// Now call update passing in the ID first then the object you are updatingNotes.update({id:$id},note);// This will PUT /notes/ID with the note object in the request payload}]);