AngularJS services are singleton objects or functions that are used to organize and share code across an application. They are a core component of AngularJS and facilitate the separation of concerns by providing a way to encapsulate reusable code, making it available to different parts of the application. Services are typically used for data fetching, business logic, and utility functions.
AngularJS provides several built-in services, such as $http for making HTTP requests,
$timeout for delaying execution, and $interval for periodic execution. These services can be injected into controllers, directives, filters, and others.
// Service to handle HTTP requests
app.service('UserService', ['$http', '$log', function ($http, $log) {
var baseUrl = 'https://jsonplaceholder.typicode.com/users';
this.getUsers = function () {
$log.log(baseUrl);
return $http.get(baseUrl);
};
}]);
// here '$scope', 'UserService' is dependency injection on controller
app.controller('myController', ['$scope', 'UserService', function ($scope, UserService) {
// Function to fetch data
$scope.getUserData = function () {
UserService.getUsers()
.then(function (response) {
$scope.users = response.data; // return the response data
}, function (error) {
console.error('Error fetching data:', error);
});
};
// Call the function to fetch data on controller load
$scope.getUserData();
}]);
You can create custom services using the service, factory, or
provider methods. Here’s an overview of each approach with examples:
1. Using the service Method
The service method creates a service by instantiating a constructor function.
// Define the module
var app = angular.module('myApp', []);
// Define a service
app.service('MathService', function() {
this.add = function(a, b) {
return a + b;
};
this.subtract = function(a, b) {
return a - b;
};
});
// Inject and use the service in a controller
app.controller('MainController', ['$scope', 'MathService', function($scope, MathService) {
$scope.addition = MathService.add(5, 3); // 8
$scope.subtraction = MathService.subtract(5, 3); // 2
}]);
2. Using the factory Method
The factory method allows for more flexible service creation by returning an object or a function.
// Define the module
var app = angular.module('myApp', []);
// Define a factory
app.factory('MathFactory', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
};
factory.divide = function(a, b) {
if (b === 0) return 'Error';
return a / b;
};
return factory;
});
// Inject and use the factory in a controller
app.controller('MainController', ['$scope', 'MathFactory', function($scope, MathFactory) {
$scope.multiplication = MathFactory.multiply(5, 3); // 15
$scope.division = MathFactory.divide(5, 0); // Error
}]);
3. Using the provider Method
The provider method provides the most flexibility, allowing for configuration during the application’s configuration phase.
// Define the module
var app = angular.module('myApp', []);
// Define a provider
app.provider('MathProvider', function() {
var precision = 1;
this.setPrecision = function(p) {
precision = p;
};
this.$get = function() {
return {
round: function(value) {
return value.toFixed(precision);
}
};
};
});
// Configure the provider
app.config(['MathProviderProvider', function(MathProviderProvider) {
MathProviderProvider.setPrecision(2);
}]);
// Inject and use the provider in a controller
app.controller('MainController', ['$scope', 'MathProvider', function($scope, MathProvider) {
$scope.roundedValue = MathProvider.round(5.678); // 5.68
}]);
Key Points
Service: A singleton object instantiated by a constructor function.
Factory: A more flexible approach where an object or function is returned.
Provider: The most configurable approach, useful for complex service configuration and setup.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
AngularJS services are singleton objects or functions that are used to organize and share code across an application. They are a core component of AngularJS and facilitate the separation of concerns by providing a way to encapsulate reusable code, making it available to different parts of the application. Services are typically used for data fetching, business logic, and utility functions.
Creating and Using Services
Built-in Services
AngularJS provides several built-in services, such as
$httpfor making HTTP requests,$timeoutfor delaying execution, and$intervalfor periodic execution. These services can be injected into controllers, directives, filters, and others.Custom Services
You can create custom services using the
service,factory, orprovidermethods. Here’s an overview of each approach with examples:1. Using the
serviceMethodThe
servicemethod creates a service by instantiating a constructor function.2. Using the
factoryMethodThe
factorymethod allows for more flexible service creation by returning an object or a function.3. Using the
providerMethodThe
providermethod provides the most flexibility, allowing for configuration during the application’s configuration phase.Key Points
Read more
Factory vs Service in AngularJS, Which one better?
Create Custom Services in AngularJS
Describe the life-cycle of AngularJs Service and Controller
Services and Dependency Injection in AngularJS