Saturday, March 12, 2016

Best practice when using $http in AngularJS


In almost every one-page-application, you will be requested to retrieve some sort of data from the server or any http url, which usually retrieves a JSON data. After reading a lot of materials and working on different projects, I have arrived to the conclusion of what may be the best practice of retrieving data. In this article I will also explain the reasons.

Before reading: This article is intended for those having moderate knowledge on AngularJS.

The power of AngularJS resides on its ability to dynamically build Web Applications rapidly.


If you have built some AngularJS applications, for sure, you wrote a lot of controllers, if you have injected $http to your controller, it was probably wrong. Why?

The Controllers need to bind the data (model) to the html page (Template), and it does not need to know the mechanism used to obtain that data.
So, the mechanism to obtain the JSON data will be encapsulated into services.
This way, we are achieving two main design principles, "decoupling" and "separation of concerns".

You always will start your angular js file with something like this:

var App = angular.module('ProfileApp', []);
The module is the container for the different parts of your app – controllers, services, filters, directives, etc.

Now, this will be the controller that, in this case retrieve a bunch of facebook profiles:



In this controller we are injecting the "ProfileService" and calling the function getProfileList() which retrieves a "promise" (explained below).
A "Promise" is a mechanism that let you defer an asynchronous action.

The service will look like this:
App.service('ProfileService',['$http',function($http){

      

        // get facebook profile list.

                this.getProfileList = function() {

                    return $http.get('http://duda-api-test.herokuapp.com/profiles').then(function(response) {   

                        return response.data;

                    });

                }

}]);

Some interesting things about this code:


  1. Despite, they are also used for the same purpose, I'm using "Services" instead of "Factories". There are a lot of good articles explaining which one should you choose. I choose "Service" since, ES6 (ES stands for ECMAScript) is more compatible with Services than Factories, and it will be much easier to migrate when the time comes.
  2. I'm using the shortcut-ed version of $http for simplicity and more important, I'm using it with "then", since the $http legacy promise methods success and error have been deprecated.
  3. I'm NOT using $q, since there is no reason to use $q.defer to create promises. Why? Because, "then" already returns a promise, therefore, it is much more readable and simple.



You can see a full working version of my "angular service JSFiddle" containing this approach.







2 comments:

  1. Nice Post! Your insight are very impressive and creative its very helpful.Thanks for sharing..
    Full Stack Online Training

    ReplyDelete
  2. great tips about full stack At SynergisticIT we offer the best Full Stack course training in california

    ReplyDelete