Angular server-side communication

$http

$http

  • core Angular Service for communcitation with remote HTTP servers;
  • can communicate via the browser's XMLHttpRequest or via JSONP;
  • works hand in hand with $q service.

$http

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

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.

*Since the returned value is a promise, you can also use then() for registering callbacks.

$http shortcut methods

$http.get

$http.head

$http.post

$http.put

$http.delete

$http.jsonp

$http.patch

$http config object

$httpProvider

$httpProvider properties

Setting HTTP Headers

The $http service will automatically add certain HTTP headers to all requests. 

The default headers can be fully configured by accesing the $httpProvider.defaults.headers configuration object which contains:

  • $httpProvider.defaults.headers.common (headers that are common for all requests)
  • $httpProvider.defaults.headers.post (header defaults for POST requests)
  • $httpProvider.defaults.headers.put (header defaults for PUT requests)
  • $httpProvider.defaults.headers.patch (header defaults for PATCH requests)

* To add headers for an HTTP method other than POST, PUT or PATCH, simply add a new object:

$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }

Transforming Requests and Responses

Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:

Request transformations:

  • If the data property of the request configuration object contains an object, serialize it into JSON format.

Response transformations:

  • If XSRF prefix is detected, strip it (see Security Considerations section below).
  • If JSON response is detected, deserialize it using a JSON parser.

Transform Response Example

//Add a new function at the end of chain
$httpProvider.defaults.transformResponse.push(function(data, headersGetter){
    //data it's already converted from an angular default transformer
    data.total = headersGetter('X-Total-Count');

    return data;
});

//Replace the entire chain
$httpProvider.defaults.transformResponse = [function(data, headersGetter){
    //assume the data is a JSON string
    var tranformedData = angular.fromJson(data);
    tranformedData.total = headersGetter('X-Total-Count');

    return tranformedData;
}];

Interceptors

Interceptors

An interceptor is a service factory that is registered with the $httpProvider by adding him to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

Interceptors

There are two kinds of interceptors (and two kinds of rejection interceptors):

  • request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
  • requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
  • response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.
  • responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
 // register the interceptor as a service
  $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
      // optional method
      'request': function(config) {
        // do something on success
        return config;
      },

      // optional method
     'requestError': function(rejection) {
        // do something on error
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      },

      // optional method
      'response': function(response) {
        // do something on success
        return response;
      },

      // optional method
     'responseError': function(rejection) {
        // do something on error
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      }
    };
  });

  $httpProvider.interceptors.push('myHttpInterceptor');

  // alternatively, register the interceptor via an anonymous factory
  $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
    return {
     'request': function(config) {
         // same as above
      },

      'response': function(response) {
         // same as above
      }
    };
  });

$resource

$resource

A factory which creates a resource object that lets you interact with RESTful server-side data sources.

Usage: $resource(url, [paramDefaults], [actions]);

//Resource Constructor provided by $resource factory
var User = $resource('/user/:id', {id:'@id'});

//new Resource instance
var user = new User({name: 'John'});

//Prototype methods from Resource class - persist to backend
user.$save().then(function(){
    //Delete the user
    user.$delete();
});

//Get existing user
var user2 = User.get({id: 2}, function(){
    user.name = 'Another name';
    user.$save();
});

* $resource it's a wrapper over $http service

Resource Factory

  • 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: false}

Resource Factory config

Resource constructor

  • The default set of resource actions optionally extended with custom actions.
  • Default actions:
    • query : {method: 'GET'}
    • get: {method: 'GET'}
    • save: {method: 'POST'}
    • remove: {method: 'DELETE'}
    • delete: {method: 'DELETE'}

Invocation:

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

* Success is called with (value, responseHeaders) . Error is called with (httpResponse).

** Class actions return empty instance with aditional properties: $promise and $resolved

*** The instance's properties are populated after the $promise is $resolved 

Resource Instance

Resource instances are instances created by invocation of the constructor with new operator, or by invocation of constructor methods 

  • The instance level-methods are prefixed with the sign
  • Instance methods have equivalent functionality with constructor's methods
  • Instance method are available only for non-GET operations

 

*Instance actions return promise of the action.

Demo

Credits

Angular server-side communication

By Alexe Bogdan

Angular server-side communication

Angular $http and $resources

  • 937