In AngularJS, services are singleton objects used for data sharing, business logic, and API communication across different components. They help in modularizing the application by keeping the controller lightweight and maintaining separation of concerns.
1. What Are AngularJS Services?
- Services in AngularJS encapsulate reusable logic.
- They follow a singleton pattern, meaning they are instantiated only once and shared across the application.
- They are typically used for:
- Fetching data from APIs.
- Sharing data between controllers.
- Performing business logic.
- Managing utility functions (e.g., logging, authentication).
2. Why Use AngularJS Services?
Reusability – Write logic once and use it across the app.
Separation of Concerns – Keep controllers focused on the view, while services handle logic.
Dependency Injection – Inject services wherever needed, improving testability.
Singleton Nature – Data remains consistent across different parts of the app.
3. Creating Services in AngularJS
AngularJS provides multiple ways to create services:
- Factory (
.factory()
) - Service (
.service()
) - Provider (
.provider()
)
4. Creating a Service Using .factory()
factory()
returns an object that contains properties and methods.
Example – Fetching Data Using Factory Service
var app = angular.module('myApp', []);
app.factory('UserService', function() {
var user = {
name: "John Doe",
age: 30
};
return {
getUser: function() {
return user;
}
};
});
app.controller('UserController', function(UserService) {
var vm = this;
vm.userData = UserService.getUser();
});
<div ng-controller="UserController as userCtrl">
<h1>{{ userCtrl.userData.name }}</h1>
<p>Age: {{ userCtrl.userData.age }}</p>
</div>
Why Use .factory()
?
- More flexible and preferred for creating objects with functions.
5. Creating a Service Using .service()
Unlike .factory()
, a service function acts as a constructor and uses this
to define properties.
Example – Using .service()
Instead of .factory()
app.service('UserService', function() {
this.name = "John Doe";
this.age = 30;
this.getUser = function() {
return { name: this.name, age: this.age };
};
});
app.controller('UserController', function(UserService) {
var vm = this;
vm.userData = UserService.getUser();
});
Why Use .service()
?
- More readable when dealing with object-oriented patterns.
6. Creating a Service Using .provider()
A .provider()
gives more configurability and is useful for setting up services before runtime.
Example – Using .provider()
for Configurable Service
app.provider('UserService', function() {
var userName = "Default User";
this.setUserName = function(name) {
userName = name;
};
this.$get = function() {
return {
getUserName: function() {
return userName;
}
};
};
});
// Configuring the service before app starts
app.config(function(UserServiceProvider) {
UserServiceProvider.setUserName("Configured User");
});
app.controller('UserController', function(UserService) {
var vm = this;
vm.username = UserService.getUserName();
});
Why Use .provider()
?
- Best for configurable services that need values set at runtime.
7. Built-in Services in AngularJS
AngularJS provides many predefined services, such as:
Service | Purpose |
---|---|
$http | Handles AJAX requests |
$timeout | Executes code after a delay |
$interval | Repeats code at intervals |
$log | Logs messages to the console |
$location | Manipulates browser URL |
$q | Handles promises for asynchronous operations |
8. Example – Making HTTP Requests Using $http
Service
The $http
service is used to fetch data from a server.
Example – Fetching Data from an API
app.factory('UserService', function($http) {
return {
getUsers: function() {
return $http.get('https://jsonplaceholder.typicode.com/users');
}
};
});
app.controller('UserController', function(UserService) {
var vm = this;
UserService.getUsers().then(function(response) {
vm.users = response.data;
});
});
<div ng-controller="UserController as userCtrl">
<ul>
<li ng-repeat="user in userCtrl.users">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</div>
Why Use $http
?
- Simplifies AJAX calls with built-in promise handling.
9. Singleton Nature of Services
Services in AngularJS follow the singleton pattern, meaning:
- The same instance is shared across all components.
- State is maintained throughout the application.
Example – Data Sharing Across Controllers
app.factory('CounterService', function() {
var counter = 0;
return {
increment: function() { counter++; },
getCount: function() { return counter; }
};
});
app.controller('FirstController', function(CounterService) {
var vm = this;
vm.increment = function() {
CounterService.increment();
};
vm.count = function() {
return CounterService.getCount();
};
});
app.controller('SecondController', function(CounterService) {
var vm = this;
vm.count = function() {
return CounterService.getCount();
};
});
<div ng-controller="FirstController as firstCtrl">
<button ng-click="firstCtrl.increment()">Increment</button>
<p>First Controller Count: {{ firstCtrl.count() }}</p>
</div>
<div ng-controller="SecondController as secondCtrl">
<p>Second Controller Count: {{ secondCtrl.count() }}</p>
</div>
Why Use a Service Here?
- The counter value is shared across both controllers.