Hello readers, Here we are going to discuss Services in Angular Js. Services are simple javascript functions and are responsible for performing a specific task. It provides a method to keep data across the lifetime of the Angular app.

What are Services in Angular Js?

Angular js supports the concepts of Separation of concerns. Services in angular Js are simple javascript functions and are responsible for performing a specific task. It provides a method to keep data across the lifetime of the Angular app. It is used to organize and share data and functions across the application.

Angular Services based on the Single Responsibility Principle (SRP) and are glued together using dependency injection (DI). The Single Responsibility principle ensures is based on the fact that each object will have only a single responsibility.

AngularJS offers many built-in services, for example,

  • $http.
  • $resource.
  • $q.
  • $anchorSrcoll.
  • $cacheFactory.
  • $locale.
  • $timeout.
  • $cookies .
  • $routeProvider.
  • $routeParams.
  • $log.

We will discuss each of above in upcoming sessions.

Syntax for defining services in Angular Js.

var app = angular.module('myApp', []);

app.service('myservice', function() {
this.fun = function (name) {
return "Hello "+name;
}

Example of Services:

Here is a simple example of Services.

<!DOCTYPE html>
<html>
<title>
Services Example
</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">

<p>Example of Services in Angular Js</p>

<h1>{{message}}</h1>

</div>

<script>
var app = angular.module('myApp', []);

app.service('myservices', function() {
 this.SayHello = function (name) {
 return "Hello "+name;
 }
});
app.controller('myCtrl', function($scope, myservices) {
 $scope.message = myservices.SayHello("Debug On Web");
});
</script>

</body>
</html>

Output:

Services

Click here to see the demo.

Conclusion:

I hope this is a useful tutorial for you. I would appreciate your feedback, comments, and suggestions.

Thank You.

Leave a Comment