Introduction of Services in AJS
- Services play a crucial role in AngularJS applications by promoting modularity, reusability, and separation of concerns.
- By encapsulating common functionality within services, we can create more maintainable and scalable applications.
Definition of Services in AJS
- In AngularJS, services are singletons that provide specific functionality or data throughout an application. They are an essential part of AngularJS architecture and are used to organize and share code across different application parts.
- In AngularJS, services are a fundamental part of the AJS framework, allowing us to organize and share code across the application.
- In AngularJS, services are objects designed to provide shared functionality across an application.
Characteristics of Services in AJS
- Services are singletons techniques, i.e., AngularJS creates service codes only once per application and then caches them for subsequent use. This ensures that there is only one instance of a service throughout the application, making it a perfect place to put reusable business logic, data access code, or utility functions.
- Services play a crucial role in AngularJS applications by promoting separation of concerns, code reusability, and testability.
- They allow us to write clean, modular, and maintainable code by keeping different parts of our application decoupled and focused on their specific responsibilities.
- Once we’ve defined a service in a program, we can inject it into controllers, directives, filters, and other services by specifying its name as a dependency. AngularJS will then provide the service instance when instantiating the dependent component, allowing us to access its properties and methods.
- AngularJS provides several built-in services, such as
$http
for making HTTP requests,$rootScope
for interacting with the root scope, and$routeParams
for accessing parameters in route templates. - Additionally, we can also create several custom services as needed using the
service
,factory
,provider
, orconstant
methods provided by AngularJS. - To use built-in service methods or a custom service method in an AngularJS application, we can inject it into the controller, directive, or another service section of the program where we need to use it.
Types of Services in AJS
AngularJS provides several types of services, including:-
In-built/Built-In Services in AJS
-
- These are services provided by AngularJS itself, such as
$http
for making HTTP requests,$timeout
for asynchronous operations,$location
for URL manipulation, etc. - AngularJS provides several built-in services, but some popular built-in services in AngularJS are as follows:-
- These are services provided by AngularJS itself, such as
-
-
-
$http: This service makes HTTP requests to remote servers. It is used for fetching data from a server or posting data to a server.
-
$location: The service provides access to the URL in the browser’s address bar. It can be used to read or change the current URL.
- $window: The $window service refers to the browser window object and is globally available in JavaScript but In AngularJS, it is not globally available. It includes various methods like alert box, prompt box, confirms box, etc.
-
$timeout: It is a service for scheduling the execution of a function to be executed after a specified delay of time.
-
$rootScope: The root scope service of the AngularJS application is the top-level scope that is accessible from all parts of the application.
-
$log: It is a simple logging service that provides methods for logging messages to the console.
-
$routeParams: A service that provides access to the parameters passed in the URL route.
-
-
Customize/Custom Service Methods
-
- We can also create several of our own custom services to meet the specific needs of our application using the
service()
,factory()
,provider()
, orconstant
methods provided by the AngularJS module. - The typical customized Services methods are as follows:-
- We can also create several of our own custom services to meet the specific needs of our application using the
-
-
-
.service()
:-
This method is used to define a service by registering it with a constructor function.
-
When AngularJS creates a service using
service()
, it instantiates the constructor function usingnew
keyword, so we can attach properties and methods directly tothis
within the constructor. - To create a custom service using the module.service() method, which defines a constructor function that will be instantiated with the
new
keyword. This is useful when we want to create an object-oriented service. for example –
-
-
-
angular.module(‘myApp’).service(‘myService’, function() {
this.someMethod = function() {
// Service logic codes here as program needed
};
});
-
-
-
.factory
:-
This method allows us to define a service by providing a factory function that returns an object or function.
-
This method gives us more control over the creation process and allows for more flexible service implementations.
- To create a custom service using the module.factory() method, which defines a factory function that returns an object or a function. Factories are more flexible than services and can return any value. for example –
-
-
-
angular.module(‘myApp’).factory(‘myFactory’, function() {
return {
someMethod: function() {
// Factory logic codes here as program needed
}
};
});
-
-
-
.provider
:-
This method is the most configurable way to define a service in AngularJS.
-
Here, providers are objects that have a
$get
method, which returns the service instance. -
This method is typically used when we need to configure a service before it’s instantiated.
-
-
.constant
:-
This method is used to define a service by registering a value that remains constant throughout the application’s lifecycle.
-
Constants are often used to store configuration values or other data that should not change.
-
- Once a service is defined/created, we can inject it into controllers, directives, or other services using AngularJS’s dependency injection mechanism. AngularJS takes care of instantiating the service and providing it wherever it’s needed.
- angular.module(‘myApp’).controller(‘MyController’, function($scope, myService) {
// Use myService codes here
myService.someMethod();
});
- angular.module(‘myApp’).controller(‘MyController’, function($scope, myService) {
-
- Custom services are useful for encapsulating reusable functionality and promoting code reuse and maintainability in our AngularJS applications.
-
Uses of Services in AJS
- Services are used to encapsulate reusable logic, such as data manipulation, business logic, or interaction with external resources like APIs.
- They promote code reusability, modularity, and maintainability by keeping the concerns of different parts of our application separate.
- They are used to encapsulate reusable business logic, data access methods, or any other functionality that needs to be shared between different parts of an application safely, such as controllers, directives, or other services.
Examples of Services in AJS
Example : AJS program to display $timeout services.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="app1" ng-controller="controller1">
<h1>{{rWord}}</h1>
</div>
<script>
var app2 = angular.module('app1', []);
app2.controller('controller1', function($scope, $timeout)
{
$scope.rWord = "Hello World!";
$timeout(function ()
{
$scope.rWord = "Hello India!";
}, 3000);
}
);
</script>
</body>
</html>
NB:
Here, '$timeout' services replace the header word 'Hello World' with 'Hello India' after 3 seconds(3000).
Example : AJS program of Digital Clock with interval 1second to display $interval services.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="app1" ng-controller="controller1">
<p>The Current Time is:</p>
<h1>{{timVal}}</h1>
</div>
<script>
var app2 = angular.module('app1', []);
app2.controller('controller1', function($scope, $interval)
{
$scope.timVal = new Date().toLocaleTimeString();
$interval(function ()
{
$scope.timVal = new Date().toLocaleTimeString();
}, 1000);
});
</script>
</body>
</html>
Example : AJS program to display $window Alert Message services.
<!DOCTYPE html>
<html>
<head>
<title>$window service</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="app1">
<div ng-controller="controller1">
<button ng-click="msg()">Click Me</button>
</div>
<script>
var app2 = angular.module('app1', []);
app2.controller('controller1',
['$scope', '$window',
function ($scope, $window)
{
$scope.msgsentence = "Use of Alert Box in AJS";
$scope.msg = function ()
{
$window.alert($scope.msgsentence);
}
}
]
);
</script>
</body>
</html>
Example : AJS program to display $window Prompt Message services.
<!DOCTYPE html>
<html>
<head>
<title>$window service</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="app1">
<div ng-controller="controller1">
<button ng-click="msg()">Click Me</button>
<p>{{fullname}}</p>
</div>
<script>
var app2 = angular.module('app1', []);
app2.controller('controller1',
['$scope', '$window',
function ($scope, $window) {
$scope.msg = function () {
var x = $window.prompt('Enter Your Message');
$scope.fullname = 'Hello ' + x;
}
}]);
</script>
</body>
</html>
Example : AJS program to display $window Confirm Message services.
<!DOCTYPE html>
<html>
<head>
<title>$window service</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="app1">
<div ng-controller="controller1">
<button ng-click="msg()">Click Me</button>
<p>{{confirmMessage}}</p>
</div>
<script>
var app2 = angular.module('app1', []);
app2.controller('controller1',
['$scope', '$window',
function ($scope, $window)
{
$scope.msg = function ()
{
var choice = $window.confirm("Are You Continue ?")
if (choice == true)
$scope.confirmMessage = 'You Accept the Confirmation';
else
$scope.confirmMessage = 'You Reject the Confirmation';
}
}
]
);
</script>
</body>
</html>
0 Comments