Angular Services


What is a Service?

A service in Angular is a special type of object or function that provides specific functionality or data and can be injected into various parts of the application. These services act as a centralized mechanism to store and manage data, perform calculations, or handle logic that should be accessible in multiple places.

Angular comes with a rich set of built-in services, one of which is $location, used for manipulating and retrieving the current URL.

Example: Using $location Service

The $location service helps you interact with the browser's URL without directly using the window.location object. This makes it more Angular-friendly by ensuring that URL changes are properly tracked within Angular's change detection system.

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, $location) {   
    $scope.currentUrl = $location.absUrl(); 
}); 

Here, $location is injected into the controller to retrieve the absolute URL of the current page.


Why Opt for Services?

Although you can use native JavaScript objects like window.location in place of Angular’s $location, Angular’s services integrate more seamlessly with Angular’s lifecycle and change detection. Using these services ensures your application behaves predictably and optimally in terms of performance.


The $http Service

Another commonly used service is $http, which allows you to easily make HTTP requests from your Angular application. It simplifies interaction with external servers by handling both requests and responses.

Example: Using $http to Fetch Data

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, $http) {   
    $http.get("data.json").then(function(response) {     
        $scope.serverData = response.data;   
        }); 
}); 

This example demonstrates how $http can be used to retrieve data from a server and assign it to a variable in your scope.


The $timeout Service

Angular’s $timeout service is a wrapper around JavaScript's setTimeout, offering better integration with Angular’s change detection cycle.

Example: Changing Content After a Delay with $timeout

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, $timeout) {   
     $scope.greeting = "Hello!";   
     $timeout(function () {    
         $scope.greeting = "How are you?";   
    }, 3000); 
}); 

The $interval Service

Similarly, $interval is a service that provides a wrapper around JavaScript’s setInterval. It allows periodic updates, such as updating a clock, without having to manually manage intervals.

Example: Using $interval to Show Real-Time Time

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, $interval) {   
    $scope.timeNow = new Date().toLocaleTimeString();   
    $interval(function() {     
        $scope.timeNow = new Date().toLocaleTimeString();   
   }, 1000); 
}); 

In this example, `$interval` is used to update the time every second, ensuring smooth synchronization with Angular's digest cycle for automatic updates.


Building Custom Services

Angular enables the creation of custom services to manage unique application logic and functionality tailored to your needs. To do so, you define a service within your module and then inject it wherever necessary.

Example: Creating a hexConvert Service

app.service('hexConvert', function() {   
    this.toHex = function(num) {     
      return num.toString(16);   
   }; 
}); 

Here, hexConvert is a custom service that converts numbers to their hexadecimal equivalent.


Using the Custom Service in a Controller

app.controller('myCtrl', function($scope, hexConvert) {   
    $scope.hexValue = hexConvert.toHex(255); 
}); 

Using a Service Inside a Filter

Once a service is created, you can inject it into filters to modify data before it’s displayed.

Example: Using hexConvert in a Custom Filter

app.filter('hexFormat', ['hexConvert', function(hexConvert) {   
    return function(input) {     
       return hexConvert.toHex(input);   
     }; 
}]); 

This filter uses the hexConvert service to format numbers as hexadecimal values.

Example: Applying the Filter in HTML

<ul>   
      <li ng-repeat="item in items">{{ item | hexFormat }}</li> 
</ul> 

By leveraging Angular's services, you can centralize business logic and facilitate code reuse, making your application more modular and maintainable.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand ANGULAR Tutorial visually:

What You'll Learn:
  • 📌 Angular Services Tutorial | Angular Services Explained | Angular Tutorial For Beginners |Simplilearn
  • 📌 Angular Tutorial - 17 - Services
Previous Next