Categories: JavascriptUI

AngularJS – How to Create & Use Custom Service

This article demonstrates how one could create custom services in AngularJS and use them within controllers or other services using dependency injection. In this article, the service demonstrated is Calculator service with just one API named as “calculate”. The API takes two numbers and operation type and calculate the result appropriately. The demo could be found on this page, http://hello-angularjs.appspot.com/angularjs-create-custom-services

Following are three key steps in creating using custom services:

  1. Create the code for service (take a look at example below showing Calculator class with a constructor, Calculator()
  2. Register the recipe or method to inject the service. Injector service uses this to inject the service
  3. Inject the new custom service in the Controller or in other services

 

Step 1: Create/Define the Service

The code below represents how to create a custom service. The Calculator class is defined with a constructor and an API namely, calculate. Other methods such as add, subtract etc are private methods of this class. The method “calculate” is invoked on the “calculator” service object that is injected into the controller component (Look at step 3).

function Calculator() {

 this.calculate = function( no1, no2, optype ) {
   var result = 0;
   switch( optype ) {
     case '+':
       result = add( no1, no2);
       break;
     case '-':
       result = subtract( no1, no2);
       break;
     case '*':
       result = multiply(  no1, no2);
       break;
     case '/':
       result = divide(  no1, no2);
       break;
     default:
   }
   return result;
 }
 var add = function( no1, no2 ) {
   return no1 + no2;
 }
 var subtract = function( no1, no2 ) {
   return no1 - no2;
 }
 var multiply = function( no1, no2 ) {
   return no1 * no2;
 }
 var divide = function( no1, no2 ) {
   return no1 / no2;
 }

}

 

Step 2: Defining Factory Method for Injecting Calculator Service

In following code, the Calculator service is created using factory method. The injector service invokes the factory method on the app, (calcApp), and obtains an instance of Calculator service. The “factory” method constructs a new service using a function with zero (as shown below) or more arguments (dependencies on other services). The return value of this function is the service instance.

It has been found many a times, that one tries and inject $scope object in function() such as function($scope) with the thought that the parameters of $scope object could be used within the service by reference. However, Angular throws error with that. With factory method, only services can be injected. And, $scope object can not be considered as service. The best practice is to pass the parameters in the method as shown in the API, calculate.

calcApp.factory('calculator', function() {
      return new Calculator();
    });

There are other ways of creating a service, the details of which could be found on this page (https://docs.angularjs.org/guide/providers).

 

Step 3: Injecting Calculator Service and Invoking the Method

Following code represents how one could inject a custom service. In the code below, “calculator” service is injected by Angular injector service. Also, pay attention to the method invocation, calculator.calculate.

var calcApp = angular.module( "calcApp", [] );
calcApp.controller( "CalculatorCtrl", [ '$scope','calculator', function($scope, calculator ) {

$scope.types = [
  { name : 'Add', value : '+' },
  { name : 'Subtract', value : '-' },
  { name : 'Multiply', value : '*' },
  { name : 'Divide', value : '/' },
  ];
 $scope.type = $scope.types[0];

 $scope.calculate = function() {
     $scope.result = calculator.calculate( $scope.no1, $scope.no2, $scope.type.value );
 }

}]);

[adsenseyu1]

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Share
Published by
Ajitesh Kumar
Tags: angularjs

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

1 month ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

1 month ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

2 months ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

2 months ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

2 months ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

2 months ago