In AngularJS, services are reusable objects or functions used to organize and share data and logic across the application. They follow a modular design pattern, promoting maintainability and scalability. This tutorial explores AngularJS services, their types, and practical applications.
For more programming tutorials, visit The Coding College, your go-to platform for learning coding and programming concepts.
What Are AngularJS Services?
Services in AngularJS are singleton objects that provide functionality or data. Once created, a service instance is shared across all components that inject it, ensuring consistency and reusability.
Key Features
- Singleton Nature: Services are instantiated only once per application lifecycle.
- Dependency Injection (DI): AngularJS injects services into controllers, directives, or other services.
- Modular Design: They separate application logic from the controller and view.
Common Use Cases
- Fetching data from APIs.
- Sharing data across components.
- Encapsulating business logic.
Built-In AngularJS Services
AngularJS provides several built-in services to simplify development.
Service Name | Description | Example Usage |
---|---|---|
$http | Makes AJAX calls to fetch or send data. | Fetch data from an API. |
$q | Helps manage asynchronous operations with promises. | Handle multiple async calls. |
$timeout | Executes code after a delay. | Create a delay in function execution. |
$interval | Executes code repeatedly at specified intervals. | Create a timer. |
$location | Parses and manipulates the browser URL. | Manage routing. |
$rootScope | Shares global data across the app. | Access global variables. |
Creating Custom Services
AngularJS allows you to create custom services using the following methods:
- Factory
- Service
- Provider
Using the $http
Service
The $http
service is a built-in AngularJS service for making HTTP requests.
Example: Fetching Data
<div ng-app="myApp" ng-controller="myCtrl">
<h2>Posts</h2>
<ul>
<li ng-repeat="post in posts">{{ post.title }}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
$scope.posts = response.data;
});
});
</script>
Output:
Displays a list of post titles fetched from the API.
Custom Service with Factory
Factories are the most common way to create custom services.
Example: Creating and Using a Factory Service
var app = angular.module('myApp', []);
app.factory('MathService', function() {
return {
square: function(num) {
return num * num;
},
cube: function(num) {
return num * num * num;
}
};
});
app.controller('myCtrl', function($scope, MathService) {
$scope.number = 3;
$scope.square = MathService.square($scope.number);
$scope.cube = MathService.cube($scope.number);
});
Usage in HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<p>Number: {{ number }}</p>
<p>Square: {{ square }}</p>
<p>Cube: {{ cube }}</p>
</div>
Output:
- Number: 3
- Square: 9
- Cube: 27
Custom Service with Service
The service
method is another way to create services. It uses a constructor function and assigns properties or methods to the this
keyword.
Example:
app.service('GreetingService', function() {
this.sayHello = function(name) {
return "Hello, " + name + "!";
};
});
app.controller('myCtrl', function($scope, GreetingService) {
$scope.greeting = GreetingService.sayHello('AngularJS');
});
Usage in HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{ greeting }}</p>
</div>
Output:Hello, AngularJS!
Custom Service with Provider
Providers are the most flexible way to create services. They allow for configuration during the app’s configuration phase.
Example:
app.provider('Greet', function() {
var greeting = "Hello";
this.setGreeting = function(newGreeting) {
greeting = newGreeting;
};
this.$get = function() {
return {
greet: function(name) {
return greeting + ", " + name + "!";
}
};
};
});
app.config(function(GreetProvider) {
GreetProvider.setGreeting("Hi");
});
app.controller('myCtrl', function($scope, Greet) {
$scope.message = Greet.greet("AngularJS");
});
Output:Hi, AngularJS!
Comparison of Factory, Service, and Provider
Feature | Factory | Service | Provider |
---|---|---|---|
Usage | Returns an object. | Uses constructor. | Offers configurability. |
Flexibility | High | Moderate | Very High |
Configuration Phase | Not possible | Not possible | Possible |
Best Practices for AngularJS Services
- Keep Services Focused
Each service should have a single responsibility. - Use Dependency Injection
Inject dependencies to keep services modular and testable. - Avoid
$rootScope
Dependency
Use$rootScope
sparingly to avoid tightly coupled components. - Write Reusable Services
Create generic services that can be reused across multiple modules.
Conclusion
AngularJS services provide a powerful way to modularize and reuse your application’s logic. Whether you use built-in services like $http
or create custom ones, services form the backbone of scalable AngularJS applications.