Intoduction to $http APIs in angularjs for beginners

Doing XHR and JSONP calls using the $http service is straightforward. Let’s consider an example of fetching JSON content with a GET request:

var futureResponse = $http.get('data.json');
futureResponse.success(function (data, status, headers, config) {
  $scope.data = data;
});
futureResponse.error(function (data, status, headers, config) {
  throw new Error('Something went wrong...');
});

First of all we can see that there is a dedicated method to issue XHR GET requests. There are equivalent methods for other types of XHRrequests as well:

  • GET: $http.get(url, config)
  • POST: $http.post(url, data, config)
  • PUT: $http.put(url, data, config)
  • DELETE: $http.delete(url, config)
  • HEAD: $http.head

It is also possible to trigger a JSONP request with $http.jsonp(url, config).

The parameters accepted by the $http methods differ slightly depending on the HTTP method used. For calls that can carry data in their body (POST and PUT) the method signature is the following one:

  • url: the URL to be targeted with a call
  • data: data to be sent with a request’s body
  • config: a JavaScript object containing additional configuration options influencing a request and a response

For the remaining methods (GET, DELETE, HEAD, JSONP) where there is no data to be sent with the request’s body, the signature becomes simpler and is reduced to two parameters only: url and config.

The object returned from the $http methods allows us to register success and error callbacks.

The JavaScript configuration object can hold different options influencing the request, response and data being transmitted. The configuration object can have the following properties (among others):

  • method: HTTP method to be issued
  • url: URL to be targeted with a request
  • params: parameters to be added to the URL query string
  • headers: additional headers to be added to a request
  • timeout: timeout (in milliseconds) after which a XHR request will be dropped
  • cache: enables XHR GET request caching
  • transformRequest, transformResponse: transformation functions that allows us to pre-process and post-process data exchanged with a back-end

You might be a bit surprised to see method and url among configuration options since those parameters can be already supplied as part of a $http methods’ signatures. It turns out that $http itself is a function that can be invoked in a generic way:

$http(configObject);

The generic form might be useful for cases where angularjs doesn’t provide a “shortcut” method (for example for PATCH or OPTIONS requests). In general we find that shortcut methods result in a more concise and easier way to read code, and we would recommend using this form over the generic one whenever possible.

Recommended :  How to do Best Coding Practices in Laravel

Request data conversion

The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.

Tip

The default data to JSON conversion mechanism ignores all properties starting with a dollar sign ($). In general, properties beginning with $ are considered “private” in angularjs. This might be problematic for some back-ends to which we need to send properties with the $ (for example, MongoDB). The workaround is to convert data manually (using the JSON.stringify method, for example).

We can see the data conversion in action by issuing a POST request to create a new user in MongoLab:

var userToAdd = {
  name:'angularjs Superhero',
  email:'[email protected]angularjs.org'
};

$http.post('https://api.mongolab.com/api/1/databases/ascrum/collec
  tions/users',
  userToAdd, {
    params:{
      apiKey:'4fb51e55e4b02e56a67b0b66'
    }
  });

This example also illustrates how HTTP query string parameters (here: apiKey) can be added to a URL.

Dealing with HTTP responses

A request can either succeed or fail and angularjs provides two methods to register callbacks to deal with the two outcomes: success and error. Both the methods accept a callback function that will be called with the following parameters:

Note

angularjs will invoke success callbacks for the HTTP responses with status ranging from 200 to 299. Responses with a status outside of this range will trigger the error callback. The redirection responses (HTTP status 3xx codes) are automatically followed by a browser.

Both success and error callbacks are optional. If we don’t register any callback a response will be silently ignored.

Response data conversion

As with request data conversions, the $http service will try to convert responses containing a JSON string into a JavaScript object. This conversion happens before invoking success or error callbacks. The default conversion behavior can be customized.

Note

In the current version of angularjs the $http service will try to perform JSON string to JavaScript object conversion on any responses that look like JSON (that is, starts with { or [ and end with ] or }).

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares