AngularJS Services Example Tutorial

Filed Under: AngularJS

Today we will look at one of the important angular concepts called AngularJS Services. In the previous tutorial, we looked at AngularJS routing feature with a simple example.

AngularJS Services

Angular services are singleton objects that carry out some sort of task. We also use AngularJS services to organize and share code across the application.

Angular Services follow Single Responsibility Principle (SRP) and are wired together using dependency injection (DI). The Single Responsibility principle ensures that each object will have only a single responsibility.

For Example, controllers are responsible for wiring model data to views. It will violate the Single Responsibility Principle, if we use controllers to carry out some other logic. Therefore, the business logic should be abstracted out into services and they are injected when needed. This makes the application more manageable and testable.

Angular offers several useful services like $http, $log, $filter etc. The inbuilt services are always prefixed with $.

In this AngularJS services tutorial, we will create our own angular service.

Creating and Registering Angular Services

Angular services are created by registering them with the module they are going to operate in.

There are three ways to create an angular service. They are using Factory, Service and Provider.

First, create a module named app using the following syntax:


var app = angular.module("app", []);

AngularJS services using Factory

The most common way to create a service is by using the Module’s Factory API. We use the factory method to create an object, add properties to it and return the same object. Later it can be injected to the components like controller, service, filter or directive.

Here is the general syntax for using Factory service.


app.factory('factoryName',function(){
         return factoryObj;
      });

Create angular services using Service

This is instantiated with the new keyword. You will be provided with an instance of the function passed to the service. This object instance becomes the service object that AngularJS registers and is injected to the required components.

We use this keyword to add properties and functions to this service object. Unlike factory method, this does not return anything.

Here is the general syntax for using Service.


app.service('serviceName',function(){ });

AngularJS services example using Provider

Providers are the only service you can pass into your .config() function. Providers are used when you want to provide module-wide configuration for your service object before making it available. It returns value by using $get() function.

Here is the general syntax for creating and configuring a Provider.


// syntax for creating a provider
app.provider('providerName',function(){ });

//syntax for configuring a provider
app.config(function(providerNameProvider){});

AngularJS Services Example

The following example demonstrates the usage of factory, service and provider services. We are going to develop a sample message service, which prints out a message using all these service APIs.

The code shown below (index.html) is our view. We need to get the serviceMsg, factoryMsg and providerMsg using the Service APIs and we use controller to wire the data to this view.


<html>
<head>
    <title>AngularJS Services Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
    <script src="main.js"></script>
</head>
<body>
<div>
    <div ng-app="mainApp" ng-controller="myController">
        <p><b>Message From Service: </b>{{serviceMsg}}</p>
        <p><b>Message From Factory: </b>{{factoryMsg}}</p>
        <p><b>Message From Provider:</b>{{providerMsg}}</p>
    </div>
</div>

</body>
</html>

The code shown below defines the services and the controller used in the application.

main.js


var app = angular.module('mainApp', []);

//define a service named myService
app.service('myService', function () {
    this.message = '';
    this.setMessage = function (newMessage) {
        this.message = newMessage;
        return this.message;
    };
});

//define factory  named 'myFactory'
app.factory('myFactory', function () {
    var obj = {};
    obj.message = '';
    obj.setMessage = function (newMessage) {
        obj.message = newMessage;
    };
    return obj;
});

//Defining a provider 'configurable'
app.provider('configurable', function () {
    var returnMessage = '';
    this.setMessage = function (newMessage) {
        returnMessage = newMessage;
    };
    this.$get = function () {
        return {
            message: returnMessage
        };
    };
});

//configuring provider
app.config(function (configurableProvider) {
    configurableProvider.setMessage("Hello, I'm From Provider");
});

//defining controller
app.controller('myController', function ($scope, myService, myFactory, configurable) {
    $scope.serviceMsg = myService.setMessage("Hello, I'm From Service");

    myFactory.setMessage("Hello, I'm From Factory ");
    $scope.factoryMsg = myFactory.message;

    $scope.providerMsg= configurable.message;
});

AngularJS Services Example code description

  1. Created a module named mainApp using angular.module(‘mainApp’, []);
  2. Defined a service using service method in the module and you can see how we added properties and function to the service object for getting the message. We used this keyword to add the properties to the service object.
  3. Defined a service using factory method in the module and returned the service object.
  4. Defined a service using provider method in the module and used $get() function to get the message.
  5. Configured the provider using the config() function in the module to set the message.
  6. Defined a controller and all the services are injected to the controller.
  7. Set the factory and service messages.
  8. Finally controller wire all the messages to the view using $scope.

Output

You will see the following output in your browser for our example services in AngularJS.

AngularJS Services example

That’s all for services in AngularJS and we will see more angular features in the coming posts.

Comments

  1. Miley Cyrus says:

    Thanks for sharing these tips! I am sure your tips really helpful!

  2. Rochaksite says:

    Very good Informative Blog ….Thanks for sharing

  3. Bhuvizerobug says:

    Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages