annuaire recherche
AngularJS API Reference auto auto/service auto/service/$injector auto/service/$provide ng ng/directive ng/directive/a ng/directive/form ng/directive/input ng/directive/input[checkbox] ng/directive/input[date] ng/directive/input[dateTimeLocal] ng/directive/input[email] ng/directive/input[month] ng/directive/input[number] ng/directive/input[radio] ng/directive/input[text] ng/directive/input[time] ng/directive/input[url] ng/directive/input[week] ng/directive/ngApp ng/directive/ngBind ng/directive/ngBindHtml ng/directive/ngBindTemplate ng/directive/ngBlur ng/directive/ngChange ng/directive/ngChecked ng/directive/ngClass ng/directive/ngClassEven ng/directive/ngClassOdd ng/directive/ngClick ng/directive/ngCloak ng/directive/ngController ng/directive/ngCopy ng/directive/ngCsp ng/directive/ngCut ng/directive/ngDblclick ng/directive/ngDisabled ng/directive/ngFocus ng/directive/ngForm ng/directive/ngHide ng/directive/ngHref ng/directive/ngIf ng/directive/ngInclude ng/directive/ngInit ng/directive/ngKeydown ng/directive/ngKeypress ng/directive/ngKeyup ng/directive/ngList ng/directive/ngModel ng/directive/ngModelOptions ng/directive/ngMousedown ng/directive/ngMouseenter ng/directive/ngMouseleave ng/directive/ngMousemove ng/directive/ngMouseover ng/directive/ngMouseup ng/directive/ngNonBindable ng/directive/ngOpen ng/directive/ngPaste ng/directive/ngPluralize ng/directive/ngReadonly ng/directive/ngRepeat ng/directive/ngSelected ng/directive/ngShow ng/directive/ngSrc ng/directive/ngSrcset ng/directive/ngStyle ng/directive/ngSubmit ng/directive/ngSwitch ng/directive/ngTransclude ng/directive/ngValue ng/directive/script ng/directive/select ng/directive/textarea ng/filter ng/filter/currency ng/filter/date ng/filter/filter ng/filter/json ng/filter/limitTo ng/filter/lowercase ng/filter/number ng/filter/orderBy ng/filter/uppercase ng/function ng/function/angular.bind ng/function/angular.bootstrap ng/function/angular.copy ng/function/angular.element ng/function/angular.equals ng/function/angular.extend ng/function/angular.forEach ng/function/angular.fromJson ng/function/angular.identity ng/function/angular.injector ng/function/angular.isArray ng/function/angular.isDate ng/function/angular.isDefined ng/function/angular.isElement ng/function/angular.isFunction ng/function/angular.isNumber ng/function/angular.isObject ng/function/angular.isString ng/function/angular.isUndefined ng/function/angular.lowercase ng/function/angular.module ng/function/angular.noop ng/function/angular.toJson ng/function/angular.uppercase ng/object ng/object/angular.version ng/provider ng/provider/$animateProvider ng/provider/$compileProvider ng/provider/$controllerProvider ng/provider/$filterProvider ng/provider/$httpProvider ng/provider/$interpolateProvider ng/provider/$locationProvider ng/provider/$logProvider ng/provider/$parseProvider ng/provider/$rootScopeProvider ng/provider/$sceDelegateProvider ng/provider/$sceProvider ng/service ng/service/$anchorScroll ng/service/$animate ng/service/$cacheFactory ng/service/$compile ng/service/$controller ng/service/$document ng/service/$exceptionHandler ng/service/$filter ng/service/$http ng/service/$httpBackend ng/service/$interpolate ng/service/$interval ng/service/$locale ng/service/$location ng/service/$log ng/service/$parse ng/service/$q ng/service/$rootElement ng/service/$rootScope ng/service/$sce ng/service/$sceDelegate ng/service/$templateCache ng/service/$timeout ng/service/$window ng/type ng/type/$cacheFactory.Cache ng/type/$compile.directive.Attributes ng/type/$rootScope.Scope ng/type/angular.Module ng/type/form.FormController ng/type/ngModel.NgModelController ngAnimate ngAnimate/provider ngAnimate/provider/$animateProvider ngAnimate/service ngAnimate/service/$animate ngCookies ngCookies/service ngCookies/service/$cookies ngCookies/service/$cookieStore ngMessages ngMessages/directive ngMessages/directive/ngMessage ngMessages/directive/ngMessages ngMock ngMock/function ngMock/function/angular.mock.dump ngMock/function/angular.mock.inject ngMock/function/angular.mock.module ngMock/object ngMock/object/angular.mock ngMock/provider ngMock/provider/$exceptionHandlerProvider ngMock/service ngMock/service/$exceptionHandler ngMock/service/$httpBackend ngMock/service/$interval ngMock/service/$log ngMock/service/$timeout ngMock/type ngMock/type/angular.mock.TzDate ngMockE2E ngMockE2E/service ngMockE2E/service/$httpBackend ngResource ngResource/service ngResource/service/$resource ngRoute ngRoute/directive ngRoute/directive/ngView ngRoute/provider ngRoute/provider/$routeProvider ngRoute/service ngRoute/service/$route ngRoute/service/$routeParams ngSanitize ngSanitize/filter ngSanitize/filter/linky ngSanitize/service ngSanitize/service/$sanitize ngTouch ngTouch/directive ngTouch/directive/ngClick ngTouch/directive/ngSwipeLeft ngTouch/directive/ngSwipeRight ngTouch/service ngTouch/service/$swipe
personnages

AngularJS: API: ngResource/service/$resource


$resource

  1. - service in module ngResource

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 the ngResource module 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 $resourceProvider like 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 : as in /user/:username. If you are using a URL with a port number (如: http://example.com:8080/api), it will be respected.

If you are using a url with a suffix, just add the suffix, like this: $resource('http://example.com/resource.json') or $resource('http://example.com/:id.json') or even $resource('http://example.com/resource/:resource_id.:format') If the parameter before the suffix is empty, :resource_id in this case, then the /. will be collapsed down to a single .. If you need this sequence to appear and not collapse then you can escape it with /\..

paramDefaults
(可选)
Object

Default values for url parameters. These can be overridden in actions methods. If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).

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 /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet?salutation=Hello.

If the parameter value is prefixed with @ then the value of that parameter will be taken from the corresponding key on the data object (useful for non-GET operations).

actions
(可选)
Object.<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:

  {action1: {method:?, params:?, isArray:?, headers:?, ...},
   action2: {method:?, params:?, isArray:?, headers:?, ...},
   ...}

Where:

  • action – {string} – The name of action. This name becomes the name of the method on your resource object.
  • method – {string} – HTTP request method. Valid methods are: GET, POST, PUT, DELETE, and JSONP.
  • params – {Object=} – Optional set of pre-bound parameters for this action. If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).
  • url – {string} – action specific url override. The url templating is supported just like for the resource-level urls.
  • isArray – {boolean=} – If true then the returned object for this action is an array, see 返回值 section.
  • transformRequest{Function(data, headersGetter)|Array.<Function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
  • transformResponse{Function(data, headersGetter)|Array.<Function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
  • cache{boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
  • timeout{number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
  • responseType - {string} - see requestType.
  • interceptor - {Object=} - The interceptor object has two optional methods - response and responseError. Both response and responseError interceptors get called with http response object. See $http interceptors.
options Object

Hash with custom settings that should extend the default $resourceProvider behavior. The only supported option is

Where:

  • stripTrailingSlashes – {boolean} – If true then the trailing slashes from any calculated URL will be stripped. (Defaults to true.)

返回值

Object

A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

  { 'get':    {method:'GET'},
    'save':   {method:'POST'},
    'query':  {method:'GET', isArray:true},
    'remove': {method:'DELETE'},
    'delete': {method:'DELETE'} };

Calling these methods invoke an $http with the specified http method, destination and parameters. When the data is returned from the server then the object is an instance of the resource class. The actions save, remove and delete are available on it as methods with the $ prefix. This allows you to easily perform CRUD operations (create, read, update, delete) on server-side data like this:

  var User = $resource('/user/:userId', {userId:'@id'});
  var user = User.get({userId:123}, Function() {
    user.abc = true;
    user.$save();
  });

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

The action methods on the class object or instance object can be invoked with the following parameters:

  • HTTP GET "class" actions: Resource.action([参数], [success], [error])
  • non-GET "class" actions: Resource.action([参数], postData, [success], [error])
  • non-GET instance actions: instance.$action([参数], [success], [error])

    Success callback is called with (value, responseHeaders) arguments. Error callback is called with (httpResponse) argument.

    Class actions return empty instance (with additional properties below). Instance actions return promise of the action.

    The Resource instances and collection have these additional properties:

  • $promise: the promise of the original server interaction that created this instance or collection.

    On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

    On failure, the promise is resolved with the http response object, without the resource property.

    If an interceptor object was provided, the promise will instead be resolved with the value returned by the interceptor.

  • $resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding.

示例

Credit card resource

     // Define CreditCard class
     var CreditCard = $resource('/user/:userId/card/:cardId',
      {userId:123, cardId:'@id'}, {
       charge: {method:'POST', params:{charge:true}}
      });

     // We can retrieve a collection from the server
     var cards = CreditCard.query(Function() {
       // GET: /user/123/card
       // server returns: [ {id:456, number:'1234', name:'Smith'} ];

       var card = cards[0];
       // each item is an instance of CreditCard
       expect(card instanceof CreditCard).toEqual(true);
       card.name= "J. Smith";
       // non GET methods are mapped onto the instances
       card.$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 well
     var newCard = new CreditCard({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 $http on the url template with the given method, params and headers. 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.

     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, Function(user) {
       user.abc = true;
       user.$save();
     });

It's worth noting that the success callback for get, query and 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:

     var User = $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 $http promise via the $promise property on the object returned

     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123})
         .$promise.then(Function(user) {
           $scope.user = user;
         });

Creating a custom 'PUT' request

In this example we create a custom method on our resource to make a PUT request

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

    // Some APIs expect a PUT request in the format URL/object/ID
    // Here we are creating an 'update' method
    app.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 $scope
    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
                                      Function($scope, $routeParams, Notes) {
   // First get a note object from the factory
   var note = Notes.get({ id:$routeParams.id });
   $id = note.id;

   // Now call update passing in the ID first then the object you are updating
   Notes.update({ id:$id }, note);

   // This will PUT /notes/ID with the note object in the request payload
    }]);

Article précédent: Article suivant: