属性
Restangular comes with defaults for all of its properties but you can configure them. So, if you don't need to configure something, there's no need to add the configuration.
You can set all these configurations in RestangularProvider
or Restangular
service to change the global configuration or you can use the withConfig method in Restangular service to create a new Restangular service with some scoped configuration. Check the section on this later.
setBaseUrl
The base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is /api/v1
. The default baseUrl is an empty string which resolves to the same url that AngularJS is running, so you can also set an absolute url like http://api.example.com/api/v1
if you need do set another domain.
setExtraFields
These are the fields that you want to save from your parent resources if you need to display them. By default this is an Empty Array which will suit most cases
setParentless
Use this property to control whether Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple /buildings/123
instead of /accounts/123/buildings/123
. This property lets you do that.
This method accepts 1 parameter, it could be:
- Boolean: Specifies if all elements should be parentless or not
- Array: Specifies the routes (types) of all elements that should be parentless. For example
['buildings']
setDefaultHttpFields
$http
from AngularJS can receive a bunch of parameters like cache
, transformRequest
and so on. You can set all of those properties in the object sent on this setter so that they will be used in EVERY API call made by Restangular. This is very useful for caching for example. All properties that can be set can be checked here: http://docs.angularjs.org/api/ng.$http#parameters
addElementTransformer
This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), the corresponding transformer will be called if it fits.
This should be used to add your own methods / functions to entities of certain types.
You can add as many element transformers as you want. The signature of this method can be one of the following:
addElementTransformer(route, transformer): Transformer is called with all elements that have been restangularized, no matter if they're collections or not.
addElementTransformer(route, isCollection, transformer): Transformer is called with all elements that have been restangularized and match the specification regarding if it's a collection or not (true | false)
setTransformOnlyServerElements
This sets whether transformers will be run for local objects and not by objects returned by the server. This is by default true but can be changed to false if needed (Most people won't need this).
setOnElemRestangularized
This is a hook. After each element has been "restangularized" (Added the new methods from Restangular), this will be called. It means that if you receive a list of objects in one call, this method will be called first for the collection and then for each element of the collection.
I favor the usage of addElementTransformer
instead of onElemRestangularized
whenever possible as the implementation is much cleaner.
This callback is a function that has 3 parameters:
- elem: The element that has just been restangularized. Can be a collection or a single element.
- isCollection: Boolean indicating if this is a collection or a single element.
- what: The model that is being modified. This is the "path" of this resource. For example
buildings
- Restangular: The instanced service to use any of its methods
This can be used together with addRestangularMethod
(Explained later) to add custom methods to an element
setResponseInterceptor
This is deprecated. Use addResponseInterceptor since you can add more than one.
addResponseInterceptor
The responseInterceptor is called after we get each response from the server. It's a function that receives this arguments:
- data: The data received got from the server
- operation: The operation made. It'll be the HTTP method used except for a
GET
which returns a list of element which will returngetList
so that you can distinguish them. - what: The model that's being requested. It can be for example:
accounts
,buildings
, etc. - url: The relative URL being requested. For example:
/api/v1/accounts/123
- response: Full server response including headers
- deferred: The deferred promise for the request.
Some of the use cases of the responseInterceptor are handling wrapped responses and enhancing response elements with more methods among others.
The responseInterceptor must return the restangularized data element.
setRequestInterceptor
This is deprecated. Use addRequestInterceptor since you can add more than one.
addRequestInterceptor
The requestInterceptor is called before sending any data to the server. It's a function that must return the element to be requested. This function receives the following arguments:
- element: The element to send to the server.
- operation: The operation made. It'll be the HTTP method used except for a
GET
which returns a list of element which will returngetList
so that you can distinguish them. - what: The model that's being requested. It can be for example:
accounts
,buildings
, etc. - url: The relative URL being requested. For example:
/api/v1/accounts/123
setFullRequestInterceptor
This is deprecated. Use addFullRequestInterceptor since you can add more than one.
addFullRequestInterceptor
This adds a new fullRequestInterceptor. The fullRequestInterceptor is similar to the requestInterceptor
but more powerful. It lets you change the element, the request parameters and the headers as well.
It's a function that receives the same as the requestInterceptor
plus the headers and the query parameters (in that order).
It can return an object with any (or all) of following properties:
- headers: The headers to send
- params: The request parameters to send
- element: The element to send
- httpConfig: The httpConfig to call with
If a property isn't returned, the one sent is used.
setErrorInterceptor
The errorInterceptor is called whenever there's an error. It's a function that receives the response, the deferred (for the promise) and the Restangular-response handler as parameters.
The errorInterceptor function, whenever it returns false
, prevents the promise linked to a Restangular request to be executed. All other return values (besides false
) are ignored and the promise follows the usual path, eventually reaching the success or error hooks.
The feature to prevent the promise to complete is useful whenever you need to intercept each Restangular error response for every request in your AngularJS application in a single place, increasing debugging capabilities and hooking security features in a single place.
var refreshAccesstoken = function() {
var deferred = $q.defer();
// Refresh access-token logic
return deferred.promise;
};
Restangular.setErrorInterceptor(function(response, deferred, responseHandler) {
if(response.status === 403) {
refreshAccesstoken().then(function() {
// Repeat the request and then call the handlers the usual way.
$http(response.config).then(responseHandler, deferred.reject);
// Be aware that no request interceptors are called this way.
});
return false; // error handled
}
return true; // error not handled
});
setRestangularFields
Restangular required 3 fields for every "Restangularized" element. These are:
- id: Id of the element. Default: id
- route: Name of the route of this element. Default: route
- parentResource: The reference to the parent resource. Default: parentResource
- restangularCollection: A boolean indicating if this is a collection or an element. Default: restangularCollection
- cannonicalId: If available, the path to the cannonical ID to use. Useful for PK changes
- etag: Where to save the ETag received from the server. Defaults to
restangularEtag
- selfLink: The path to the property that has the URL to this item. If your REST API doesn't return a URL to an item, you can just leave it blank. Defaults to
href
Also all of Restangular methods and functions are configurable through restangularFields property.
All of these fields except for id
and selfLink
are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property.
setMethodOverriders
You can now Override HTTP Methods. You can set here the array of methods to override. All those methods will be sent as POST and Restangular will add an X-HTTP-Method-Override header with the real HTTP method we wanted to do.
setJsonp
By setting this value to true, both get
and getList
will be performed using JSonp instead of the regular GET.
You will need to add the 'JSON_CALLBACK' string to your URLs (see $http.jsonp). You can use setDefaultRequestParams
to accomplish this:
RestangularProvider.setDefaultRequestParams('jsonp', {callback: 'JSON_CALLBACK'});
setDefaultRequestParams
You can set default Query parameters to be sent with every request and every method.
Additionally, if you want to configure request params per method, you can use requestParams
configuration similar to $http
. For example RestangularProvider.requestParams.get = {single: true}
.
Supported method to configure are: remove, get, post, put, common (all)
// set params for multiple methods at once
Restangular.setDefaultRequestParams(['remove', 'post'], {confirm: true});
// set only for get method
Restangular.setDefaultRequestParams('get', {limit: 10});
// or for all supported request methods
Restangular.setDefaultRequestParams({apikey: "secret key"});
setFullResponse
You can set fullResponse to true to get the whole response every time you do any request. The full response has the restangularized data in the data
field, and also has the headers and config sent. By default, it's set to false. Please note that in order for Restangular to access custom HTTP headers, your server must respond having the Access-Control-Expose-Headers:
set.
// set params for multiple methods at once
Restangular.setFullResponse(true);
Or set it per service
// Restangular service that uses setFullResponse
app.factory('RestFulResponse', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setFullResponse(true);
});
});
// Let's use it in the controller
app.controller('MainCtrl', function(Restangular, RestFulResponse) {
// Uses full response configuration
RestFulResponse.all('users').getList().then(function(response) {
$scope.users = response.data;
console.log(response.headers);
});
});
设置默认头 setDefaultHeaders
You can set default Headers to be sent with every request. Send format: {header_name: header_value}
// set default header "token"
RestangularProvider.setDefaultHeaders({token: "x-restangular"});
setRequestSuffix
If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like /users/123.json
you can add that .json
to the suffix using the setRequestSuffix
method
setUseCannonicalId
You can set this to either true
or false
. By default it's false. If set to true, then the cannonical ID from the element will be used for URL creation (in DELETE, PUT, POST, etc.). What this means is that if you change the ID of the element and then you do a put, if you set this to true, it'll use the "old" ID which was received from the server. If set to false, it'll use the new ID assigned to the element.
setEncodeIds
You can set here if you want to URL Encode IDs or not. By default, it's true.