Off the Ridge code

Off the Ridge Code Newsletter

Search

How to Angular – Part 4.5 – How to use AngularJS Asynchronous Http service.

Published April 24, 2015 in AngularJS - 0Comments

In Part 4.5 I’ll talk about

AngularJS Asynchronous Http service.

In part 4 of ‘How to Angular,’ I presented services and how to retrieve a photo from the gravatar.com service. But, what if you wanted to use a service to retrieve remote data, in JSON, asynchronously? Have no fear, the $http.get service facilities server communication using XMLHttpRequest object.

Briefly, $http service returns a promise which can be used to call the ‘.then’ method and register your own callbacks.
In other words, your own callbacks will be called once the asynchronous call via $http.get returns – whether successfully or not.

To illustrate this I’m going to call the GitHub API service at api.github.com and retrieve a user for the AngularJS team; the full url call will be: https://api.github.com/users/angularjs”.

1. The first thing I’m going to do is create a new service called: ‘gitHubUserLookup’

app.factory('gitHubUserLookup', function($http) {
        return {
                lookupUser: function(user) {
                return $http.get("https://api.github.com/users/" + user)
                            .then(function(response) {
                             return response;
               },
              // error handler
              function(response) {
                      return response;
            });
        }
     }
});

2. Then I’m going to inject it (via dependency injection) into our controller:

var MyFirstController = function($scope, $http, userData, userGravatar, <strong>gitHubUserLookup</strong>){...}

3. Next, I’m going to add a function inside the controller that will call into our service:

var getGitHubUser = function(username) {

           gitHubUserLookup.lookupUser(username).then(onLookupComplete, onError);
};

As I’ve mentioned, the $http service returns a promise on which we can call ‘.then’ method and pass in two callbacks, one for the ‘success’ method and the other for the ‘error’ method.

The onLookupComplete will get called once the request successfully completes:

 var onLookupComplete = function(response) {
          $scope.user = response.data;
          $scope.status = response.status;

    };
5. Finally I’m going to display the retrieved data back on our page:
 
     <div>Github lookup status: {{status}}</div>
     <div>
       <pre>{{user | json}}
            {{error}}

     </div>
If there are any errors, then, they will be displayed as well.

Code Example

– Happy coding!

– Sebastian