AngularJS Services

In AngularJS, services are reusable objects or functions used to organize and share data and logic across the application. They follow a modular design pattern, promoting maintainability and scalability. This tutorial explores AngularJS services, their types, and practical applications.

For more programming tutorials, visit The Coding College, your go-to platform for learning coding and programming concepts.

What Are AngularJS Services?

Services in AngularJS are singleton objects that provide functionality or data. Once created, a service instance is shared across all components that inject it, ensuring consistency and reusability.

Key Features

  1. Singleton Nature: Services are instantiated only once per application lifecycle.
  2. Dependency Injection (DI): AngularJS injects services into controllers, directives, or other services.
  3. Modular Design: They separate application logic from the controller and view.

Common Use Cases

  • Fetching data from APIs.
  • Sharing data across components.
  • Encapsulating business logic.

Built-In AngularJS Services

AngularJS provides several built-in services to simplify development.

Service NameDescriptionExample Usage
$httpMakes AJAX calls to fetch or send data.Fetch data from an API.
$qHelps manage asynchronous operations with promises.Handle multiple async calls.
$timeoutExecutes code after a delay.Create a delay in function execution.
$intervalExecutes code repeatedly at specified intervals.Create a timer.
$locationParses and manipulates the browser URL.Manage routing.
$rootScopeShares global data across the app.Access global variables.

Creating Custom Services

AngularJS allows you to create custom services using the following methods:

  1. Factory
  2. Service
  3. Provider

Using the $http Service

The $http service is a built-in AngularJS service for making HTTP requests.

Example: Fetching Data

<div ng-app="myApp" ng-controller="myCtrl">
    <h2>Posts</h2>
    <ul>
        <li ng-repeat="post in posts">{{ post.title }}</li>
    </ul>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $http.get('https://jsonplaceholder.typicode.com/posts')
            .then(function(response) {
                $scope.posts = response.data;
            });
    });
</script>

Output:
Displays a list of post titles fetched from the API.

Custom Service with Factory

Factories are the most common way to create custom services.

Example: Creating and Using a Factory Service

var app = angular.module('myApp', []);
app.factory('MathService', function() {
    return {
        square: function(num) {
            return num * num;
        },
        cube: function(num) {
            return num * num * num;
        }
    };
});

app.controller('myCtrl', function($scope, MathService) {
    $scope.number = 3;
    $scope.square = MathService.square($scope.number);
    $scope.cube = MathService.cube($scope.number);
});

Usage in HTML:

<div ng-app="myApp" ng-controller="myCtrl">
    <p>Number: {{ number }}</p>
    <p>Square: {{ square }}</p>
    <p>Cube: {{ cube }}</p>
</div>

Output:

  • Number: 3
  • Square: 9
  • Cube: 27

Custom Service with Service

The service method is another way to create services. It uses a constructor function and assigns properties or methods to the this keyword.

Example:

app.service('GreetingService', function() {
    this.sayHello = function(name) {
        return "Hello, " + name + "!";
    };
});

app.controller('myCtrl', function($scope, GreetingService) {
    $scope.greeting = GreetingService.sayHello('AngularJS');
});

Usage in HTML:

<div ng-app="myApp" ng-controller="myCtrl">
    <p>{{ greeting }}</p>
</div>

Output:
Hello, AngularJS!

Custom Service with Provider

Providers are the most flexible way to create services. They allow for configuration during the app’s configuration phase.

Example:

app.provider('Greet', function() {
    var greeting = "Hello";

    this.setGreeting = function(newGreeting) {
        greeting = newGreeting;
    };

    this.$get = function() {
        return {
            greet: function(name) {
                return greeting + ", " + name + "!";
            }
        };
    };
});

app.config(function(GreetProvider) {
    GreetProvider.setGreeting("Hi");
});

app.controller('myCtrl', function($scope, Greet) {
    $scope.message = Greet.greet("AngularJS");
});

Output:
Hi, AngularJS!

Comparison of Factory, Service, and Provider

FeatureFactoryServiceProvider
UsageReturns an object.Uses constructor.Offers configurability.
FlexibilityHighModerateVery High
Configuration PhaseNot possibleNot possiblePossible

Best Practices for AngularJS Services

  1. Keep Services Focused
    Each service should have a single responsibility.
  2. Use Dependency Injection
    Inject dependencies to keep services modular and testable.
  3. Avoid $rootScope Dependency
    Use $rootScope sparingly to avoid tightly coupled components.
  4. Write Reusable Services
    Create generic services that can be reused across multiple modules.

Conclusion

AngularJS services provide a powerful way to modularize and reuse your application’s logic. Whether you use built-in services like $http or create custom ones, services form the backbone of scalable AngularJS applications.

Leave a Comment