http

Making a web request is an essential part of most JavaScript applications. AngularJS makes it very easy for us to make these requests, using the $http service, provided out of the box. Lets set up our base AngularJS application:

(function(){
    var app = angular.module('ExampleHttpRequest', []);
})();

Now lets add an Angular factory, to provide the rest of our application access to the web service (http endpoint):

(function(){
    var app = angular.module('ExampleHttpRequest', []);

    // webService factory to make $http calls
    app.factory('webService', ['$http', function($http){
        var url = 'http://example.webservice.com/api';
        return {
            get: function(){
                return $http.get(url);
            },
            update: function(data_object){
                return $http.post(url, data_object)
            }
        }
    }]);
})();

Now that we have our factory, we can create a controller to access the factory return functions. From there we will be able to use the returned data in our view:

(function(){
    var app = angular.module('ExampleHttpRequest', []);

    // webService factory to make $http calls
    app.factory('webService', ['$http', function($http){
        var url = 'http://example.webservice.com/api';
        return {
            get: function(){
                return $http.get(url);
            },
            update: function(){
                return $http.post(url)
            }
        }
    }]);

    // Controller to call webService data to view
    app.controller('ExampleController', ['webService', '$scope', function(webService, $scope){
        // Notice the 'webService' injection,
        // this is how we use the factory within this controller.

        $scope.returnedData; // Binds data to scope

        // Get request function bound to view
        $scope.getData = function(){
            webService.get()
                .success(function(response){
                    $scope.returnedData = response;
                })
                .error(function(error){
                    // Handle error here
                })
        };

        // POST request function bound to view
        $scope.updateData = function(name, email){
        // Data object to POST
        var payload = {
            name: name,
            email, email
        };

        // Calling the update method, and passing the payload
        webService.update(payload)
            .success(function(response){
                console.log(response);
            })
            .error(function(error){
                // Handle error here
            })
        };

    }]);

})();

Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *