AngularJS - $http & $resource Services
-
Upload
eyal-vardi -
Category
Technology
-
view
15.772 -
download
2
description
Transcript of AngularJS - $http & $resource Services
Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual
C#blog: www.eVardi.com
Angular Communication
Agenda
$http $http default values Headers Transforming Interceptors Caching
$resource Resource Factory Resource Constructor Resource Instance
כאן לחץ נוספים לפרטים
$http
$http Service The AngularJS XHR API follows what is
commonly known as the Promise interface.
Use the then method to register callbacks, and these callbacks will receive a single argument – an object representing the response.
$http({ method: 'GET', url: '/someUrl' }) .success(function (data, status, headers, config) { // this callback will be called asynchronously // when the response is available }) .error(function (data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. });
$http Shortcut methods Complete list of shortcut methods:
$http.get $http.head $http.post $http.put $http.delete $http.jsonp
$http.get('/someUrl').success( successCallback );$http.post('/someUrl', data).success( successCallback );
$httpProvider Properties The defaults value for all $http requests.
Setting Defaults HTTP Headers The $http service will automatically add certain
HTTP headers to all requests.
angular.module('MyApp', []). config(function ($httpProvider) { // Remove the default AngularJS X-Request-With header delete $httpProvider.defaults.headers.common['X-Requested-With']; // Set DO NOT TRACK for all Get requests $httpProvider.defaults.headers.get['DNT'] = '1'; });
$http.get('api/user', { // Set the Authorization header. In an actual app, you would // get the auth token from a service. headers: {'Authorization': 'Basic Qzsda231231'}, params: {id: 5}}).success(function() { // Handle success });
Transforming Requests & Responses Request default transformations:
Response default transformations:
function (d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }
function (data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data); } return data;}
Response interceptors The interceptors are service factories that are
registered with the $httpProvider by adding them to the $httpProvider.responseInterceptors array.
// register the interceptor as a service$provide.factory('myHttpInterceptor', function ($q, dependency1, dependency2) { return function (promise) { return promise.then(function (response) { // do something on success
return response; },
function (response) { // do something on error if (canRecover(response)) { return responseOrNewPromise } return $q.reject(response); }); }});$httpProvider.responseInterceptors.push('myHttpInterceptor');
// register the interceptor via an anonymous factory$httpProvider.responseInterceptors.push(function ($q, dependency1, dependency2) { return function (promise) { // same as above }});
$http Caching To enable caching, set the configuration
property cache to true.
When the cache is enabled, $http stores the response from the server in local cache.
Next time the response is served from the cache without sending a request to the server.
$http.get('http://server/myapi', { cache: true}).success(function() { // Handle success });
Configuring Your Request Further You can configure your request further
through the optional configuration object passed to the requests.
$http({ method: string, url : string, params: object, data : string or object, headers: object, // or an array of functions. transformRequest: function transform(data, headersGetter), // or an array of functions. transformResponse: function transform(data, headersGetter), cache: boolean //or Cache object, timeout: number, withCredentials: boolean});
$httpBackend HTTP backend used by the service that
delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.
You should never need to use this service directly, instead use the higher-level abstractions: $http or $resource.
During testing this implementation is swapped with mock $httpBackend which can be trained with responses.
$http Service
$resource
$resource Service in ngResource A factory which creates a resource object
that lets you interact with RESTful server-side data sources.
Installation: angular-resource.js angular.module('app', ['ngResource']);
$resource( url [, paramDefaults] [, actions] );
Create a Resource $resource( url [, paramDefaults] [,
actions] );
var User = $resource('/user/:userId', { userId:
'@id' });
var user = User.get({ userId: 123 }, function () {
user.abc = true;
user.$save();
});
Resource Factory
ResourceConstruct
or
ResourceInstance
Prototypemethod
Successcallback
Resource Factory $resource( url [, paramDefaults] [,
actions] );
url - A parametrized URL template with parameters prefixed by : as in /user/:username.
paramDefaults - Given a template /path/:verb and parameter
{verb:'greet', salutation:'Hello'} results in URL /path/greet ? salutation=Hello.
Actions - Hash with declaration of custom action that should extend the default set of resource actions. action: {method:?, params:?, isArray:?, headers:? }
action – {string} – The name of action. Method – GET,POST,DELETE & JSONP Params - Optional set of pre-bound parameters for this
action. isArray - bool
Resource Constructor The default set of resource actions optionally
extended with custom actions.
Default actions:
{ 'get' : {method:'GET' }, 'save' : {method:'POST'}, 'query' : {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} };
var User = $resource('/user/:userId');
ResourceConstruct
or
Resource Factory
Resource Constructor
Resource Constructor Methods Expected up to 4 arguments params
object, data object, success function, error function.
User.get ( paramsObj, successFn, errorFn );
User.query ( paramsObj, successFn, errorFn );
// With Data Object
User.save (paramsObj, dataObj, successFn,
errorFn );
User.remove(paramsObj, dataObj, successFn,
errorFn );
User.delete(paramsObj, dataObj, successFn,
errorFn );
Resource Execution (Angular Code) Resource functions return object with
two properties: $promise and $resolved.
The two “then” function insert the response to the value object.
var promise = $http(httpConfig) .then(function success(response) { }, function error(respones) { }) .then(function responseInterceptor(response) { }, function responseErrorInterceptor(response) { });
value.$promise = promise;value.$resolved = false;
return value;
The request details
ResourceInstance
Resource Instance Structurevar card = Card.get( function () { card.name = "value"; card.$save(); });
The response data
The resource instance object methods
The card object combined the response and resource methods.
Instance vs. Constructor The instance level-methods are prefixed with
the $ character.
Both the methods have the equivalent functionality.var User = $resource('/user/:userId', { userId: '@id'
});
var user = User.get({ userId: 123);
Users.delete( {} ,
user);
Users.remove( {} , user
)
Users.save( user );
user.
$delete();
user.$remove()
user.$save();
=
$resource Service
Thankseyalvardi.wordpress.com
Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.e4d.co.il