AngularJS supports the concepts of "Separation of Concerns" using services. Services provide us a method to keep data across the lifetime of the Angular application. Angular services are substitutable objects that are wired together using dependency injection. We can use services to organize and share code across our app. Services are JavaScript functions that are responsible for specific tasks only. Services provide us a method to communicate data across the controllers in a consistent way. It provides individual entities that are maintainable and testable. Services are singleton objects and they get instantiated only once per application; controllers and filters only call them on an as-required basis. Services are singleton objects; that means each component dependent on a service gets a reference to the single instance generated by the service factory.
AngularJS provide many inbuilt services like $animate, $http, $route, $window, $location, $compile, $controller, etc.
Let us take some example of inbuilt services.
$http:
AngularJS provides $http control which works as a service to read data from the server. The $http is a core AngularJS service that is used to communicate with the remote HTTP service via browser’s XMLHttpRequest object or via JSONP.
Example:
- <html>
-
- <head>
- <title>Angular JS Includes</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Ajax Demo</h2>
- <div ng-app="app" ng-controller="Employee"><span>{{Message}}</span><br/><span>{{Status}}</span><br/>
- <br/></div>
- <script>
- var obj = angular.module('app', []);
- obj.controller('Employee', function($scope, $http)
- {
- $http({
- method: 'GET',
- url: 'index.html'
- }).then(functionsuccessCallback(response)
- {
- $scope.Message = response.data;
- $scope.Status = response.status;
-
- }, function errorCallback(response)
- {
- alert("UnsuccessFull call!");
- });
- });
- </script>
- </body>
-
- </html>
Index.HTML: This is $Ajax Example.
Output:
$window:
$window refers to the browser’s window object. In Angular we always refer window through the $ window service, so it may be overriddenor removed for testing.
Example:
- <html>
-
- <head>
- <title>Angular JS Includes</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <scrip tsrc="angular.min.js">
- </script>
- </head>
-
- <body ng-app="app">
- <h2>AngularJS $Window Example</h2>
- <div ng-controller="mycontroller">
- <input type="text" ng-model="message" aria-label="greeting" />
- <button ng-click="doGreeting(message)">ALERT BOX</button>
- </div>
- <script>
- var obj = angular.module('app', []);
- obj.controller('mycontroller', ['$scope', '$window', function($scope, $window) {
- $scope.message = 'I am $window Service!';
- $scope.doGreeting = function(message)
- {
- $window.alert(message);
- };
- }]);
- </script>
- </body>
-
- </html>
Output:
$document:
The $document is a jQuery wrapper for the browser’s
window.object method.
Example:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body ng-app="app">
- <h2>AngularJS $document Example</h2>
- <div ng-controller="myController">
- <span id="pan">Pankaj Kumar Choudhary</span>
- <p>
- <bng-bind="title">
- </b>
- </p>
- <p>
- <bng-bind="windowTitle">
- </b>
- </p>
- </div>
- <script>
- var obj = angular.module('app', []);
- obj.controller('myController', ['$scope', '$document', function($scope, $document)
- {
- $scope.title = $document[0].title;
- $scope.windowTitle = angular.element(window.document)[0].title;
- }]);
- </script>
- </body>
-
- </html>
Output:
Way to define User Services:
Here are the ways to define the services.
- factory
- service
- provider
- value
Factory:
Usin the factory method, we first define a factory and then assign a method to it. A factory is a simple function which allows us to add some logic before creating the object and at last we return this object. It is a collection of function similar to a class. It can be used in multiple controllers with constructor function.
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Service Example</h2>
- <div ng-app="mainApp" ng-controller="CalcController">
- <p>Enter First number:
- <inputtype="number" ng-model="number1" />
- </p>
- <p>Enter Second number:
- <inputtype="number" ng-model="number2" />
- </p>
- <button ng-click="multiply()">Multiply</button>
- <p>Result: {{result}}</p>
- </div>
- <script>
- var mainApp = angular.module("mainApp", []);
-
- mainApp.factory('MathService', function()
- {
- var factory = {};
-
- factory.multiply = function(a, b)
- {
- return a * b
- }
- return factory;
- });
- mainApp.controller('CalcController', function($scope, MathService)
- {
- $scope.multiply = function()
- {
- $scope.result = MathService.multiply($scope.number1, $scope.number2);
- }
- });
- </script>
- </body>
-
- </html>
Output:
Service:
Using service method we define a service and after that assign a method to this service. A service is a constructor function which creates the object using a new keyword and we can add function and property to this object using this keyword.
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Service Example</h2>
- <div ng-app="mainApp" ng-controller="CalcController">
- <p>Enter First number:
- <input type="number" ng-model="number1" />
- </p>
- <p>Enter Second number:
- <input type="number" ng-model="number2" />
- </p>
- <button ng-click="multiply()">Multiply</button>
- <p>Result: {{result}}</p>
- </div>
- <script>
- var mainApp = angular.module("mainApp", []);
- mainApp.service('MathService', function()
- {
- this.multiply = function(a, b)
- {
- return a * b
- }
- });
- mainApp.controller('CalcController', function($scope, MathService)
- {
- $scope.multiply = function()
- {
- $scope.result = MathService.multiply($scope.number1, $scope.number2);
- }
- });
- </script>
- </body>
-
- </html>
Output:
We can also inject an already available service to it. In the below example we insert a multiply_data method into a service that already exists in factory service.
Example:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Service Example</h2>
- <div ng-app="mainApp" ng-controller="CalcController">
- <p>Enter First number:
- <input type="number" ng-model="number1" />
- </p>
- <p>Enter Second number:
- <input type="number" ng-model="number2" />
- </p>
- <button ng-click="multiply()">Multiply</button>
- <p>Result: {{result}}</p>
- </div>
- <script>
- varmainApp = angular.module("mainApp", []);
-
- mainApp.factory('MathService_Factory', function()
- {
- var factory = {};
-
- factory.multiply_data = function(a, b)
- {
- return a * b
- }
- return factory;
- });
-
- mainApp.service('MathService', function(MathService_Factory)
- {
- this.multiply = function(a, b)
- {
- returnMathService_Factory.multiply_data(a, b);
- }
- });
- mainApp.controller('CalcController', function($scope, MathService)
- {
- $scope.multiply = function()
- {
- $scope.result = MathService.multiply($scope.number1, $scope.number2);
- }
- });
- </script>
- </body>
-
- </html>
Output:
Provider:
A provider is used to create a configurable service object and value returned using the $get() function. We should use the provider method when we need to provide module-wise configuration for your service object before making it available.
Example:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Service Example</h2>
- <div ng-app="mainApp" ng-controller="CalcController">
- <p>Multiply of 79 and 13 is </p>
- <p>Result: {{result}}</p>
- </div>
- <script>
- varmainApp = angular.module("mainApp", []);
-
- mainApp.provider('configurable', function()
- {
- var multi = 0;
- this.multiply = function(a, b)
- {
- multi = a * b;
- };
- this.$get = function()
- {
- return
- {
- data: multi
- };
- };
- });
- mainApp.config(function(configurableProvider)
- {
- configurableProvider.multiply(79, 13);
- });
- mainApp.controller('CalcController', function($scope, configurable)
- {
- $scope.result = configurable.data;
- });
- </script>
- </body>
-
- </html>
Output:
Value:
A value service is used to provide a value. It does exactly what we would expect it to and plays a key part in designing flexible, modular Angular applications.
Example:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <script src="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Service Example</h2>
- <divng-app="mainApp" ng-controller="CalcController">
- <p>{{message}}</p>
- <p>Result: {{result}}</p>
- </div>
- <script>
- varmainApp = angular.module("mainApp", []);
-
- mainApp.value("valueId", 79 * 13);
- mainApp.value("message", "Multiply of 79 and 13 is")
- mainApp.controller('CalcController', function($scope, valueId, message) {
- $scope.result = valueId;
- $scope.message = message;
- });
- </script>
- </body>
-
- </html>
Output:
Example:
- <html>
-
- <head>
- <title>Angular JS Example</title>
- <scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
- </script>
- <scriptsrc="angular.min.js">
- </script>
- </head>
-
- <body>
- <h2>AngularJS Service Example</h2>
- <divng-app="mainApp" ng-controller="CalcController">
- <p>Enter First number:
- <inputtype="number" ng-model="number1" />
- </p>
- <p>Enter Second number:
- <inputtype="number" ng-model="number2" />
- </p>
- <buttonng-click="Result()">Result</button>
- <p>Multiplication: {{multiply}}</p>
- <p>Addition: {{addition}}</p>
- <p>Substraction: {{substraction}}</p>
- <p>Divison: {{divison}}</p>
-
- </div>
- <script>
- varmainApp = angular.module("mainApp", []);
-
- mainApp.factory('MathService', function() {
- var factory = {};
-
- factory.multiply = function(a, b) {
- return a * b
- }
- return factory;
- });
-
- mainApp.service('addition', function() {
- this.add = function(a, b) {
- return a + b
- }
- });
-
-
- mainApp.provider('configurable', function() {
- var sub = 0;
- this.substraction = function(a, b) {
- sub = a * b;
- };
- this.$get = function() {
- return {
- data: sub
- };
- };
- });
- mainApp.config(function(configurableProvider)
- {
- configurableProvider.substraction(79, 13);
- });
-
-
-
- mainApp.value("valueId", 79 / 13);
-
- mainApp.controller('CalcController', function($scope, MathService, addition, configurable, valueId)
- {
- $scope.Result = function()
- {
- $scope.multiply = MathService.multiply($scope.number1, $scope.number2);
- $scope.addition = addition.add($scope.number1, $scope.number2);
- $scope.substraction = configurable.data;
- $scope.divison = valueId;
- }
- });
- </script>
-
- </body>
-
- </html>
Output:
In the above example we used factory, service, value and provider services.
Read more articles on AngularJS: