Angular Services and Controllers

AngularJS has nearly 30 built-in services. In this blog we will see the most commonly used services. Service factory generates a single object or a function which represents the service to the rest of the application. 

Location: Location service has methods that return information about the location of the current page. 

HTTP: This service is used in almost all applications to make requests to the server. This service helps your application handle the response.

Timeout: This is the AngularJS version of window.setTimeout function.

AJAX and service calls.

You can create a customized Service to make AJAX calls.


Example:

app.service(employee, function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

The Controller :

module.controller('MyCtrl', function($scope, myService) {

    myService.getEmployees().then(function(employees) {

        $scope.employees = employees;

    });

});

The Service:

module.factory('myService', function($http) {

   return {

        getEmployees: function() {

             //return the promise directly.

             return $http.get('/employees)

                       .then(function(result) {

                            //resolve the promise as the data

                            return result.data;
                        });
        }
   }
});

In the example above the Controller “MyCtrl” is calling the service “myService '' with a function call “getEmployees()”. The service here is calling API or Service Endpoint using HTTP request.