Dependency Injection (DI) and Services are two core features of AngularJS that allow developers to build modular, testable, and maintainable applications. This tutorial will walk you through the concepts of DI in AngularJS, the various built-in services, and how to create custom services using the factory
and service
methods.
Table of Contents
- What is Dependency Injection?
- Using AngularJS Services
- Creating a Custom Service with
factory
- Creating a Custom Service with
service
- Injecting Services into Controllers
- Conclusion
What is Dependency Injection?
Dependency Injection (DI) is a design pattern in which a component is provided with its dependencies instead of creating them internally. In AngularJS, DI allows you to inject dependencies, like services and other modules, into controllers and directives, making your code more modular and testable.
AngularJS takes care of creating and managing instances of dependencies and provides them where needed. You simply need to specify what dependencies are required in the function’s parameters.
Using AngularJS Services
AngularJS offers a variety of built-in services, such as $http
for making HTTP requests, $timeout
for handling time delays, and $interval
for setting up intervals. These services are injected into components where they are needed, enabling reusability and reducing redundancy.
Here’s a simple example of injecting the $http
service into a controller to fetch data from an API:
angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
$scope.posts = response.data;
});
});
Creating a Custom Service with factory
AngularJS allows you to create custom services using factory
or service
. Using factory
, you define a function that returns an object, which acts as the service. This is useful when you want to encapsulate logic and data in a reusable way.
Here’s how you can create a custom service with factory
:
angular.module('myApp', [])
.factory('MathService', function() {
var service = {};
service.square = function(number) {
return number * number;
};
return service;
});
This example creates a MathService
with a square
method. You can then inject this service into controllers and other components to use its methods.
Creating a Custom Service with service
Another way to create a custom service in AngularJS is by using the service
method. The service
function is instantiated with the new
keyword, and you can define methods on the service’s this
context.
Here’s how to create a custom service using service
:
angular.module('myApp', [])
.service('CalculatorService', function() {
this.add = function(a, b) {
return a + b;
};
this.subtract = function(a, b) {
return a - b;
};
});
In this example, CalculatorService
has two methods: add
and subtract
. The service
syntax is generally used when creating more complex services with multiple methods and properties.
Injecting Services into Controllers
Once a custom service is created, you can inject it into controllers and other components where it’s needed. AngularJS uses dependency injection to resolve the service dependencies by name, so it’s essential to keep the parameter name consistent.
Here’s how to inject the CalculatorService
created earlier into a controller:
angular.module('myApp', [])
.controller('CalcController', function($scope, CalculatorService) {
$scope.number1 = 5;
$scope.number2 = 3;
$scope.addNumbers = function() {
$scope.result = CalculatorService.add($scope.number1, $scope.number2);
};
$scope.subtractNumbers = function() {
$scope.result = CalculatorService.subtract($scope.number1, $scope.number2);
};
});
HTML for Using CalculatorService in Controller
<div ng-controller="CalcController">
<input type="number" ng-model="number1" />
<input type="number" ng-model="number2" />
<button ng-click="addNumbers()">Add</button>
<button ng-click="subtractNumbers()">Subtract</button>
<p>Result: {{ result }}</p>
</div>
In this example, the CalcController
uses CalculatorService
to perform addition and subtraction. The addNumbers
and subtractNumbers
methods in the controller call the corresponding service methods.
Conclusion
Dependency Injection and Services are essential parts of AngularJS, providing a structured way to inject dependencies and manage application logic. By creating custom services and using AngularJS’s built-in services, you can modularize and reuse your code more effectively. Services can be easily injected into controllers, filters, and directives, allowing you to build powerful, maintainable AngularJS applications.