AngularJS - $http & $resource Services

25
Eyal Vard CEO E4D Solutions L Microsoft MVP Visu C# blog: www.eVardi.c Angular Communication

description

AngularJS - $http & $resource Services

Transcript of AngularJS - $http & $resource Services

Page 1: AngularJS - $http & $resource Services

Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual

C#blog: www.eVardi.com

Angular Communication

Page 2: AngularJS - $http & $resource Services

Agenda

$http $http default values Headers Transforming Interceptors Caching

$resource Resource Factory Resource Constructor Resource Instance

Page 4: AngularJS - $http & $resource Services

$http

Page 5: AngularJS - $http & $resource Services

$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. });

Page 6: AngularJS - $http & $resource Services

$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 );

Page 7: AngularJS - $http & $resource Services

$httpProvider Properties The defaults value for all $http requests.

Page 8: AngularJS - $http & $resource Services

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 });

Page 9: AngularJS - $http & $resource Services

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;}

Page 10: AngularJS - $http & $resource Services

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 }});

Page 11: AngularJS - $http & $resource Services

$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 });

Page 12: AngularJS - $http & $resource Services

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});

Page 13: AngularJS - $http & $resource Services

$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.

Page 14: AngularJS - $http & $resource Services

$http Service

Page 15: AngularJS - $http & $resource Services

$resource

Page 16: AngularJS - $http & $resource Services

$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] );

Page 17: AngularJS - $http & $resource Services

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

Page 18: AngularJS - $http & $resource Services

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

Page 19: AngularJS - $http & $resource Services

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

Page 20: AngularJS - $http & $resource Services

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 );

Page 21: AngularJS - $http & $resource Services

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

Page 22: AngularJS - $http & $resource Services

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.

Page 23: AngularJS - $http & $resource Services

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();

=

Page 24: AngularJS - $http & $resource Services

$resource Service

Page 25: AngularJS - $http & $resource Services

Thankseyalvardi.wordpress.com

Eyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.e4d.co.il