AngularJS — Services
What are Services?
Services are singletons that provide reusable functionality.
Factory
app.factory('MathService', function() {
return {
add: function(a, b) { return a + b; },
multiply: function(a, b) { return a * b; }
};
});
// Usage
app.controller('MyController', function($scope, MathService) {
$scope.result = MathService.add(5, 3);
});
Service
app.service('UserService', function($http) {
this.getUsers = function() {
return $http.get('/api/users');
};
this.createUser = function(user) {
return $http.post('/api/users', user);
};
});
Provider
app.provider('ConfigService', function() {
var apiUrl = '';
this.setApiUrl = function(url) {
apiUrl = url;
};
this.$get = function($http) {
return {
get: function(path) {
return $http.get(apiUrl + path);
}
};
};
});
// Config
app.config(function(ConfigServiceProvider) {
ConfigServiceProvider.setApiUrl('https://api.example.com');
});
Built-in Services
| Service | Description |
|---|---|
| $http | HTTP requests |
| $scope | Data model |
| $rootScope | Root scope |
| $timeout | setTimeout |
| $interval | setInterval |
| $location | URL manipulation |
Mini Practice
- Create a factory
- Create a service
- Use $http service
- Inject services into controllers
Up Next
Continue with Dependency Injection — DI in AngularJS.
Related Topics
Frequently Asked Questions about Services
What is Services in AngularJS?
Services is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Services?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Services.
Why is Services important in AngularJS?
Services is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.