Developing custom Services
Blog

AngularJS: Developing custom Services

This is the fifth post in my series on the AngularJS; have a look at my initial posts covering ‘An intro to AngularJS’, ‘data-binding methods’, ‘Modules & controllers' and 'Filters'.

Considering the series is getting a bit longer, but it has immense importance as these tutorials are written in such a way to help you develop the understanding of Angular and its various components. Let’s move towards another important component of AngularJS - Services.

In a layman language, AngularJS Services is a piece of code (either business logic or objects) that can be used by an Angular application. 

Key Points:

  • It keeps your controller lightweight & makes logic that would be independent of the controller. 
  • Services only instantiated once. (the same instance is used during application cycle).
  • Services are not instantiated by default but when a controller refers to services it gets instantiated if it is not instantiated earlier.
  • A Controller can use multiple services and one service can also use another service.

Types of Services in AngularJS

1. Built-in Services: AngularJS by default provide core services, such as  $http, $log, $location angularjs etc.

2. Custom-services: These services are developed by developers to achieve certain business logic in the form of service. 

In this blog cum tutorial, we will build custom services and in the next, I will walk you through built-in services of AngularJS. 

Long story short, there are three different ways to develop custom services.

Factory: While creating services, a developer is responsible to create a service name and register the service factory function for the Angular module. Check out how to create your own custom service and call them directly to your controller. 

Sample code

Using the above source code, we can create a service name and register it to the service factory function.

The above source code has factory service that is created under the module. Where call service object with null value gets initiated and assign that service object for all the service members and return the same object. The returned object can be used directly by the controller. It passes the return object directly to the controller as a parameter. 

Once the value is available in the controller parameter then we can easily access the member function of that service as below code sample.

Service: Service is similar to the factory service. But let me tell you How does it make a difference over a selection of the right service. There is a major difference between AngularJs service vs factory service. In the service factory, we don’t need to create an additional service object and a new member function can be added directly to service definition similar to our controller, where we define member function. Also, member function gets instantiated automatically and sends the response to the controller parameter. 

The only difference between service and factory is that service object declaration. Here you don’t need to create an object and Angular takes care of - how member function gets instantiate and send to the controller as a parameter as well as minor syntax changes.

We can go with any of the service/factory.

Provider:  At this moment you must be thinking of What is a Provider in AngularJS. Let me clear you, In Angular Provider is another way to develop custom services. It is one of the core services in Angular in which services and factory are depended on. The provider has a lot of customization options compared to services and factory. Remember whenever we create custom services using factory/service, it automatically gets called to the provider in the background. 

A provider is really helpful whenever there is a service call. It helps you in initializing the configuration before any service call. In this scenario, Provider is the best option. Use Provider only when you need to instantiate some sort of configuration information or use factory/service.
 

Myapp.config provides configuration for service "TaxServiceProvider". Suffix for a service provider with 'Provider'. App configuration gets registered before the controller and services. So next time when the app controller gets instantiated it looks for service. Service is built with the Provider. While in the Bootstrap process, Provider (service) looks for configuration and executes the service.

Let’s start building a sum of two numbers using Services:

In the below source, we are implementing a simple addition of two numbers and business login using services in AngularJS.

Below we have two sources: 

1. an_page.html: Is a view 
2. an.js: implemented factory service
 

Code Explanation: In the View, we are providing two input boxes with one addition button. By default, the value of a and b will be taken up from hardcoded value, which is written directly on the controller.
 $scope.a =20;
 $scope.b =30;

When someone tries to change the value of any of the input fields the view also gets changed.
 

Service Code output

You could also initialize the same in View using ng-init. Instead of writing business logic or the addition of two numbers function inside the controller, create factory service and implement logic in the same.

As mentioned earlier, the basic rule of creating Factory service is to:
 
1. Create a blank object.
2. Assign method to that object
3. Return object so that the same could be passed over the controller as an argument.

an_page.htmlan.js

Let’s implement the same services using the service method.

As mentioned earlier, we don’t need to create any new object. We can directly add the member to the service. Note that an instance of service is auto-created by AngularJS.
 

& same could be passed to the controller as an argument.

Below is the source code for an.js

Moving to the next methodology of a service creation - Provider. It’s similar to factory service but allows you to add some additional configuration. Here sumServiceProvider is the provider name followed by service name + postfix(Provider keyword) else Angular will never instantiate your service configuration. As soon as Angular find service as a provider, it starts searching for configuration and instantiate some additional configuration.

MyApp.config(['sumServiceProvider', function (sumServiceProvider) {
    ………
}]);

Let’s build our provider service. This is similar to factory service.
this.$get = function () { 
}

The above function gets executed automatically by AngularJS that allows you to implement a service object as well as methods.
 

Source Code:


So far we have learned about different variants of services as well as ways to create a service and when to use them. This installment will give you an in-depth knowledge of AngularJS Services and will help you build a strong foundation. This post is a follow-up to our previous post Filters in AngularJS. Hope you enjoyed reading.
 

GitHub source code: https://github.com/xaiwant/AngularJS-Services

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch