$http in Angular

$http in Angular

xkcd

$http is an Angular service that make HTTP requests easy and convenient. $http is a wrapper for the XMLHttpRequest and JSONP browser functionality. It is quite similar to jQuery's ajax implementation, so you should have no trouble learning it. $http (and most other Angular built-in services, in fact) uses promises, so to understand it better you may want to refer to this page.


Quick note: You may find lots of code snippets online that use .success() and .error() methods on $http instead of .then(). As of Angular v1.4.4, these success and error promise methods have been deprecated. From the AngularJS v1.4.4 $http docs:


GET

Make sure to connect this with a proper HTML file so that the code will run:

angular.module('myApp', [])

.controller('myController', ["$scope", "$http", function ($scope, $http) {
    $http.get('http://pokeapi.co/api/v1/pokemon/1')
        .then(function (response) {
            console.log(response.data);
        });
}]);

Notice that there is no ; after the $http.get(...). This is important, because $http.get(...) actually returns a promise. The code above could just as well have been written like this:

angular.module('myApp', [])

.controller('myController', ["$scope", "$http", function ($scope, $http) {
    // myRequest saves the promise object returned by $http.get().
    var myRequest = $http.get('http://pokeapi.co/api/v1/pokemon/1');
    
    // We tell the code what to come back and finish doing once the promise is fulfilled.
    myRequest.then(function (response) {
        console.log(response.data);
    });
}]);

The response that's included in the callback is an object that contains all kinds of information about the response you receive. You can access the data that gets sent to you directly by using the data attribute of the response object, but there are others that you may find useful. See Angular's $http documentation for more info. (See the "General Usage" section)

Adding search parameters

Have you seen a url that included parameters from a search you've performed? They usually look something like http://www.myclothingsite.com/?color=red&material=wool&season=winter, and it's a way to send additional parameters to the server so that it can further filter the information it returns to you. In the case above, it seems like we're filtering the available clothing to only show red wool winter clothes.

Above, we included the url as the only parameter to our $http.get(). In fact, it's the only required parameter to that method. However, we can also add a second (optional) parameter to $http.get() that contains a configuration object. Check out the documentation and scroll down to the "Usage" section (about halfway down the page) for all the possible config options you can set. There you'll find the params option:

A GET request with search params looks something like this:

$http.get(url, {params: {"color": "red, "material": "wool", "season": "winter}}).then(...

which sends a GET request that looks like a request to http://www.myclothingsite.com/?color=red&material=wool&season=winter.

Note: In reality, it's still sending the request to the base url of http://www.myclothingsite.com/, but the server get the additional query string information we passed in after the ? and parses through it to return more specific results.

POST

$http can do POST requests too:

angular.module('myApp', [])

.controller('myController', ["$scope", "$http", function ($scope, $http) {
    var postData = {
        msg: 'hello word!'
    };

    $http.post('/someUrl', postData)
        .then(function (response) {
            // do something with the results
        });
}]);

$http automatically converts data to and from JSON format so you don't have to worry about JSON.parse and JSON.stringify.

Error Handling

Web requests often result in errors and $http offers a way to deal with that problem. The .then() promise handler can take an optional second parameter, an error callback, which works in much the same way as the required success callback:

function successCallback(response) {
    console.log(response.data);
}

function errorCallback(reponse) {
    console.log(response.status);
}

$http.get('http://pokeapi.co/api/v1/pokemon/1')
    .then(successCallback, errorCallback);

However, you'll more commonly see anonymous functions put in as parameters instead, just like before. Only this time, we have 2 functions, both written on-the-fly, as parameters to the .then() promise handler:

$http.get('http://pokeapi.co/api/v1/pokemon/1')
    .then(function (response) {
        // What to do if the promise is successfully resolved
        console.log(response.data);
    }, function (response) {
        // What do to if the promise can't be fulfilled for whatever reason.
        console.log("There was an error: " + response.status + " " + response.statusText);
});

Only one of the two callbacks will be called for a given request. If there is an error, the second errorCallback parameter is called and the successCallback will be skipped. The errorCallback is only called if the response contains an error status (4XX or 5XX, and maybe 3XX).

Custom Requests

If you need to add request headers, you can use the base $http() function. Instead of just passing a url you give a whole request object:

var req = {
    method: 'POST',
    url: 'http://example.com',
    headers: {
        'Content-Type': 'application/json'
    },
    data: {
        test: 'test'
    }
}

$http(req).then( /*successCallback*/ );