top of page
index-1-1.jpg

AngularJS service types with examples

In this article I will show with code examples how we can create different AngularJS service types (value, factory, service, provider, constant). We will go through all of them one by one. But one thing we need to keep in mind is; Angular services are “Lazy Instantiated” and “Singletons”.

Service in AngularJS

In Angular a service is used to organize and share our code across application. It is the best place to put all our business logic. Service can be injected easily in another services or controller. Most of us are familiar with $http as it is widely used. It is built by Angular. But we can create our own services. So let's take a deep dive and understand different AngularJS service types.

AngularJS Service Types

There are 5 different ways to create services in Angular:

1. Value

2. Factory

3. Service

4. Provider

5. Constant

Let’s have a look at each AngularJS service type one by one with code example.

1. AngularJS Value

This is the simplest Angularjs service type that we can create and use. It is just like a key value pair. Or like a variable that has some value. It just stores a single value. Assume we have a service that displays user name. Let us see how we can create this service.

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

Using Value:

We can use the service anywhere by injecting, for simplicity we are injecting in a controller and using it, here is how it looks like:

app.controller("MainController",function($scope, username){
   $scope.username=username;
});

In this example we have created a username value service and used it in MainController.

2. AngularJS Factory

As we have seen Value service, they are very easy to write but it lacks many important features. So next service type we will take a look at is “Factory” service. By creating factory service we can inject many other services in it, unlike Value service we cannot add any dependency in it. So here is how to create:

app.factory("username",function(){

   var name="John";
   return {
       name:name
   }
});

The above code shows how we can create factory service. As it takes a function, so we can inject as many dependencies as needed in that function. Also we can include any methods needed in this type of service. And the function must return some object as in our example we have returned an object with property name. So let us take a look at how we can use this service:


Using Factory:

We had returned an object from service which had a property name so we could access it and use it anywhere needed. Let’s see how we can use it in controller:

app.controller("MainController",function($scope, username){
   $scope.username=username.name;
});

We are assigning the username from factory service to our scope username.

3. AngularJS Service

The service service works same as the factory. But instead of a function it receives a Javascript class/a constructor function as argument. So let us start with the example, suppose we have a function like this:

function FooBar(foo){
   this.variable="value";
}

Now we want to convert it into a service, first let's take a look at how can we do this with “Factory” method?

app.factory("FooBarService",["foo" ,function(foo){
   return new FooBar(foo);
}]);

So in this typical way we will create its new instance and return it. Also we have injected “foo” as a dependency in factory service.

So let us see how we can achieve this via service type:

app.service("FooBarService",["foo", FooBar]);

So we have called service method on module and provided name of the service, and provided the dependency and name of function in array.

So we have looked at the use of service type. Although it is also not too flexible but can be used in these types of scenarios.

4. AngularJS Provider

The next type of service we have is provider. It is the parent of all the service types in AngularJS except the constant which we will discuss next after provider. It is the core service type, and other services are built on top of it. It is a little complex but more configurable. It is defined as a custom and must implement $get method. The main use of provider service is when we want to expose API for application-wide configuration which must be configured before starting the application.

Let’s take a look at the basic example:

app.provider('authentication', function() {

   var username = "John";

   return {

       set: function(newUserName) {
           username = newUserName;
       },

       $get: function() {
           function getUserName() {
               return username;
           }

           return {
               getUserName: getUserName
           };
       }

   };

});

In this example we have initialized a provider with name authentication. And it also implements a $get function, which returns a method getUsername which in turns return the private variable called username. This also has a setter we can set the username on application startup as follows:

app.config(["authenticationProvider", function(authenticationProvider) {
   authenticationProvider.set("David");
}]);

Notice that we have named “authenticationProvider” in the config method but our provider name was “authentication”. So while configuring the provider we need to put “Provider” as a suffix in provider name. This is an indication to Angular we want to configure the provided provider. And then we have called the set method which we have wrote and assigned a new user name.

5. AngularJS Constant

As it’s name depicts it provides a way for declaring constants in our application and we can use them anywhere needed by just adding it as a dependency. There are many areas of application where we want to use constants like some base urls, application name, some configurations, etc. So we just define them once and use them anywhere we need. This technique lets us define at one place, so that a later change the value doesn't have us change on all places, we simply just change the value of constant. So here is how we can define or create constants:

app.constant('applicationName', 'Service Tutorials');

So it is just as simple in creation; as for using we just add dependency where we want to use it.


Summary

In this article we had gone through different AngularJS service types provided by Angular. Each of them has their own use cases, pros and cons. But the most commonly used is AngularJS Factory service as it meets all our needs; the other ones can also be used depending on the requirements. Please feel free to put any questions and queries below.

Recent Posts

See All

Creating Custom Directives In AngularJS

Directive is a core feature in AngularJS framework and the framework provides different directives like ng-repeat, ng-bind, ng-controller. As directives are an important part of AngularJS, we will hav

AngularJS: Cross Component Communication

In this article we will discuss different techniques for communicating across different components in angular i.e directives, controllers. It’s a common problem that you need some type of communicatio

bottom of page