$http is one of the simplest tools to query remote resources, making your application more dynamic.

$http is available in the native package of AngularJS.

$http is a complete tool that can be easily configured thanks to $httpProvider, and can be setup in config phase of your application, making it possible to define the tool behavior throughout the whole application:

app.config(function ($httpProvider) {
    //here we can use $httpProvider
});

Handling of call success/failure.

Often a front-end application developed in AngularJs, inquiring a back-end service, needs to respect the back-end rules. Depending on the type and format of supported calls, it may be needed to manage both calls with positive (success) and negative (failure) outcome.

For example, a remote endpoint returning the latest posted news, may return the following result, in case of successful call:

[{
  "status": "ok",
  "time": 1.045,
  "content": [
   {
      "id":825415,
      "title":"At quam qui nihil alias perferendis consequatur error.",
      "summary":"Et quod et in et impedit temporibus quia iste autem nihil qui excepturi nihil aperiam totam blanditiis voluptatem vero id laudantium consequuntur possimus ut.",
      "timestamp":1408043802000,
      "author":"user16"
   },
   {
      "id":556512,
      "title":"Libero maiores velit consequatur tenetur qui neque aut consequatur.",
      "summary":"Accusantium sit est suscipit culpa voluptas ut maxime odit sit hic dolore placeat molestias illo similique sapiente omnis autem.",
      "timestamp":1407957402000,
      "author":"user3"
   }]     
}]

and the following in case of failed call:

[{
  "status": "error",
  "time": 0.765,
  "message": "the service is not available"   
}]

If you want that your application is able to correctly manage such results in an unique point, you need to setup the proper configuration of $http interceptors:

//we can set the $http interceptors:
app.config(function ($httpProvider) {
  $httpProvider.interceptors.push(function($q) {
    return {
    'response': function(response) {
        // return only the content property
        return response.content;
      },
     'responseError': function(rejection) {
        // return only the error messate
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      }
    };
  });
});

If you need to implement different endpoints with different "behaviors", you might find more useful to setup several interceptors, using the right one, based upon the different integrated endpoints. In this way you will be able to read the results (success/failure), according to the integrated endpoint, and your code will be highly scalable.

Here you are a concrete example:

// register the interceptor as a service
$provide.factory('interceptorA', function($q, dependency1, dependency2) {
  return {
    'response': function(response) {
      // do something on success
      return response;
    },
   'responseError': function(rejection) {
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    }
  };
});
//interceptor with a dependecy
$provide.factory('interceptorB', function($q, $myDependecyB) {
  return {
    'response': function(response) {
      // do something on success
      return $myDependecyB.parse(response);
    }
  };
});
//i want to use the intercepor B
$httpProvider.interceptors.push('interceptorB');

Gabriele Mittica

Developer at Corley S.r.l , Website , Git home page , @gabrielemittica , Linkedin profile
Passionate startupper, Cloud developer and amstaff lover. Worldwide geekka traveler!

All articles by Gabriele Mittica

Comments

comments powered by Disqus

cloudparty

Follow Us