Angular Services
AngularJS is a JavaScript Framework, which is very powerful and its library is written in JavaScript. This framework is used to make single page applications. From this definition, you should get an idea that if we want to make a Single Page application, AngularJS is the answer as the most powerful JavaScript Framework. AngularJS extends HTML with new attributes. AngularJS allows us to write the applications in a clean Model-View-Controller way.
AngularJS Services
A Service is a function or an object; it is limited to our AngularJS application. We can make our own Services and can use one of many inbuilt Services. The Services are injected, using dependency injection mechanism. AngularJS has many inbuilt Services. Services are JavaScript functions, which are responsible to do a specific task only. This is the property of individual identity, which is maintainable and testable. Thus, making separation of concerns possible, i.e. the property of AngularJS. Some examples of the inbuilt Services are $https, $route, $location, $window etc. Angular only instantiates a Service when an application component depends on it. Each component is dependent on a Service, which gets a reference to the single instance generated by the Service factory.
Using an inbuilt service
Let’s use an inbuilt Service to check what will be the benefit and how we can use the Services. Let’s use $location, $location is a Service that has methods, which returns information about the location of the current Webpage. Now, we will also see the use of dependency injection mechanism. The Service will be defined as a dependency.
Example
Service (Service.js)
- var app = angular.module('myApp', []);
- app.controller('customersCtrl', function($scope, $location) {
- // $scope.myUrl = $location.absUrl();
- $scope.myCurrentUrl= $location.absUrl();
- });
View
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Angular Services</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
- <script src="Service.js"></script>
- </head>
- <body>
- <div ng-app="myApp" ng-controller="customersCtrl">
- <p>The url of this page is:</p>
- <p>{{myCurrentUrl}}</p>
- </div>
- </body>
- </html>
Now, if we run this, we will get an output, as shown below.
Here, in this example, we have used inbuilt Service $location that has the method, which returns the current location of the Web page.
Creating a Service
Now, the question arises: What if we don’t want to use inbuilt Services and want to create our own Service for some functionality? How can we achieve that? We can do this by creating our own Services. We can create the Services, using three ways.
- By using factory
- By using Service
- By using provider
First of all, we create a module named myApp,
- var myApp = angular.module("myApp", []);
Using Factory Method
Syntax
- myApp.factory('factoryName',function(){
- return factoryObj;
- });
Example
- myApp.service('serviceName',function(){ });
- Example:
- myApp.service('SumService', function (MathService) {
- this.sum = function (a) {
- return MathService.Sum(a, a);
- }
- });
In this method, we have first defined a factory and then we have assigned a method to the factory.
Using Service Method
In this, a new keyword is used to instantiate it. We will get an instance of the function passed to the Service. This object instance becomes the Service Object that AngularJS registers and is injected, wherever required. This keyword is used to add properties and functions to this Service object.
Syntax
- myApp.service('serviceName',function(){ });
Example
- myApp.service('SumService', function (MathService) {
- this.sum = function (a) {
- return MathService.Sum(a, a);
- }
- });
In this method, we have defined a Service and then assign method to it. This keyword adds properties and functions to the Service object here.
Using Provider
The Providers are the only Service that we pass into .config() function. These are used only when we have to provide module wide configuration for the Service object before making it available. It uses $get() function to return the value.
Syntax
- myApp.provider('providerName',function(){ })
For configuring a provider,
- app.config(function(providerNameProvider){});
Now, we will see how we can use them.
Let’s understand this with an example given below.
View
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
- <!--<script src="MyService.js"></script>-->
- <script src="MyService.js"></script>
- </head>
- <body>
-
- <div ng-app="myApp" ng-controller="myController">
- <p>Message From Angular Service: {{service}}</p>
- <p>Message From Angular Factory: {{factory}}</p>
- <p>Message From Angular Provider:{{provider}}</p>
- </div>
-
-
- </body>
- </html>
Service (MyService.js)
- var app = angular.module('myApp', []);
-
-
- app.service('myAngularService', function () {
- this.message = '';
- this.setMessage = function (newMessage) {
- this.message = newMessage;
- return this.message;
- };
- });
-
-
- app.factory('myAngularFactory', function () {
- var obj = {};
- obj.message = '';
- obj.setMessage = function (newMessage) {
- obj.message = newMessage;
- };
- return obj;
- });
-
-
- app.provider('myAngularP', function () {
- var returnMessage = '';
- this.setMessage = function (newMessage) {
- returnMessage = newMessage;
- };
- this.$get = function () {
- return {
- message: returnMessage
- };
- };
- });
-
-
- app.config(function (myAngularPProvider) {
- myAngularPProvider.setMessage("This is using Provider");
- });
-
-
- app.controller('myController', function ($scope, myAngularService, myAngularFactory, myAngularP) {
- $scope.service = myAngularService.setMessage("this is using Service");
-
- myAngularFactory.setMessage("This is using Factory ");
- $scope.factory = myAngularFactory.message;
-
- $scope.provider = myAngularP.message;
- });
Now, we can see all the three ways. If we run this, we will get the output given below.
We have injected the Service as a dependency here. By using Service method, we get an instance of a function passed to “module.service” and by using factory method, we get the value, which is returned by invoking the function reference, which is is passed to module.factory.
In this article, we have seen how the Services can be created as per use and how can we use inbuilt Services. Provide your valuable feedback after going through the article.