XHR and Server side communication using AngularJS

Angular comes bundled with a wrapper around the XMLHttpRequest (abbreviated as XHR) called $http. We use $http to make AJAX requests. The $http object is a library that helps you make HTTP requests and then parse the response.

Let’s understand $http with an example. Consider the following code:

If we run the above code, it will make a GET request to the server at ‘http://geekhours.com/api‘ with the parameter api_key ‘121345’.

XHR requests are asynchronous. What this means is that the application will not be paused and will wait for response from the server. The advantage of asynchronous requests is that the user can continue to use the application while the data is being fetched from the server.

Once the data comes back from the server, in general, there are two ways to deal with it:

  1. Pass a callback function. This is a function that will be called when the HTTP request completes.
  2. Use a promise. This is the approach Angular takes.

Promises

Promises are objects that help make working with async code feel like we’re writing synchronous code. Angular uses promises extensively, so it is important to get familiar with how to use them.

We use three methods when we use promises:

The .then() method gets called when we receive response with no errors. The .catch() method gets called when there is an error with the response. As one would expect, the .finally() method gets called regardless of the result.

Example

 Don’t use the $http object inside a controller, instead implement it with a service.

Note : $http executes HTTP requests in an asynchronous manner, which means that you can not be sure about the time when you’ll get an answer from the server. $q is a service that provides you the capability to execute multiple asynchronous tasks one after another. That being said they conceptually do have nothing in common.

The following Plunker demonstrates $http and promises in AngularJS : https://plnkr.co/edit/d8T8uO?p=preview

Top