articles

Home / DeveloperSection / Articles / Services and Dependency Injection in AngularJS

Services and Dependency Injection in AngularJS

Services and Dependency Injection in AngularJS

Anubhav Kumar116 15-May-2024

Services

In software engineering, a service is a self-contained unit of functionality that performs a specific task or provides a particular capability. It can be thought of as a module or component that encapsulates related functionality. Services can range from simple utilities like logging or data validation to complex business logic components or external integrations like database access or API calls. The use of services promotes modularity, reusability, and separation of concerns in software architecture.

 

Dependency Injection (DI)

Dependency Injection is a design pattern and a technique used to implement the inversion of control (IoC) principle in software development. In DI, the dependencies of a component (e.g., a class or a service) are provided from outside rather than being created internally. This promotes loose coupling between components and makes them easier to test and maintain.

There are different forms of DI, including constructor injection, setter injection, and method injection. The key idea behind DI is that components should not create or manage their dependencies directly but should instead rely on an external entity (often called a container or injector) to provide those dependencies.

 

Combining Services and Dependency Injection:

  1. In many modern software architectures, services are often instantiated and managed using dependency injection frameworks or containers.
  2. Dependency injection allows services to declare their dependencies, and the DI container is responsible for providing those dependencies when a service is instantiated.
  3. This approach simplifies the management of dependencies, promotes modular design, and enables easier unit testing and maintenance.

 

There are some Built-in services and their usage

ServiceDescription
$httpUsed for making XMLHttpRequest (XHR) to the server and handling responses.
$qProvides a framework for promise-based asynchronous operations.
$timeoutExecutes a function after a specified delay.
$intervalExecutes a function repeatedly at specified intervals.
$rootScopeRepresents the root scope of the AngularJS application and provides methods for event handling.
$scopeRepresents the scope of a controller or directive.
$locationProvides access to the URL in the browser's address bar.
$routeAllows defining routes for the application and mapping them to controllers and templates.
$routeParamsProvides access to parameters passed in the URL when using $route.
$filterAllows formatting and filtering data in templates using AngularJS filters.
$logProvides a logging service for outputting messages to the console.
$exceptionHandlerHandles exceptions that occur within AngularJS code.
$injectorManages dependencies and provides instances of services.
$compileCompiles an HTML string or DOM into a template function.
$templateCacheProvides a cache for storing and retrieving HTML templates.

 

Use of $http Service: 

In AngularJS, the $http service is used to make AJAX requests to fetch or send data to a server. It provides methods for all HTTP request types, such as GET, POST, PUT, DELETE, etc.

Example -

<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm")
    .then(function(response) {
      $scope.myWelcome = response.data;
    });
  });
</script>

 

Use of $timeout Service:

The $timeout service is AngularJS' version of the window.setTimeout function.

Example -

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

 

Use of $interval Service

The $interval service is AngularJS' version of the window.setInterval function.

Example -

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

 

Use of $log Service 

The $log service allows you to log messages to the console.

Example -

$log.debug('Debug message');
$log.log(message);

 

Use of $filter Service 

The $filter service formats data for display in views.

Example -

$scope.formattedDate = $filter('date')(new Date(), 'yyyy-MM-dd');

 

Creating custom services with DI (Dependency Injection)

Create an index.html file and add HTML and AngularJS code.

 

Step 1.

Create an HTML file, add some necessary code like HTML, head, and body tag, and add the angular JS CDN and bootstrap cdn for better UI and paste this bellow code in the body tag to generate UI for the users list.

 

    <div class="container" ng-app="myApp" ng-controller="myController">
        <h2>Dependency injection and its importance example</h2>
        <hr>
        <div class="row g-3">
            <div class="col-12 ">
                <div class="d-flex flex-column flex-md-row justify-content-md-between">
                    <h1>Users List</h1>
                    <div>
                        <input type="search" data-ng-model="search" placeholder="Search user" class="form-control"
                            autofocus="true" />
                    </div>
                </div>
                <hr>
                <div class="row row-cols-1 row-cols-md-3 g-4">
                    <div class="w-100 py-3"
                        data-ng-if="(filteredUsers = (users | orderBy:'id':true | customFilter:search)).length == 0">
                        <div class="d-flex justify-content-center fw-bold">
                            <div class="text-center">
                                <p class=" fs-2 ">
                                    <span class="me-2">πŸ˜•</span>
                                    No records were found</p>
                                <p class="fw-normal">try somthing new keywords</p>
                            </div>
                        </div>
                    </div>
                    <div class="col" data-ng-repeat="user in filteredUsers">
                        <div class="card h-100">
                            <div class="card-header bg-transparent border-success position-relative">
                                <span
                                    class="fw-bold px-2 position-absolute end-0 me-2 bg-black rounded-pill text-white">{{$index
                                    + 1}}</span>
                                <p class="d-flex flex-wrap m-0">
                                    <span class="bi bi-envelope me-1"></span>
                                    {{user.email}}
                                </p>
                            </div>
                            <div class="card-body">
                                <h5 class="card-title">{{user.name}}, <small
                                        class="text-black-50">({{user.username}})</small></h5>
                                <address class="card-text">
                                    <span data-ng-repeat="(key, value) in user.address" ng-if="key !== 'geo'">
                                        {{key}} - {{value}},
                                    </span>
                                </address>
                                <p class="mb-1"><span class="bi bi-globe me-1"></span><a
                                        href="https://www.{{user.website}}" target="_blank">{{user.website}}</a></p>
                                <p class="mb-1"><span
                                        class="bi bi-briefcase-fill me-1"></span><span>{{user.company.name}}</span></p>
                            </div>
                            <div class="card-footer">
                                <p class="mb-1"><span
                                        class="bi bi-phone-vibrate-fill me-1"></span><span>{{user.phone}}</span></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Step 2.

Next, create a script tag in the body tag and paste the code below to generate the angular js custom service, filter, and controller.

 

Create β€˜myApp’ module in this code.

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

Create UserService  with dependency injection to get data from APIs. 

// Service to handle HTTP requests
app.service('UserService', ['$http', '$log', function ($http, $log) {
    var baseUrl = 'https://jsonplaceholder.typicode.com/users';
    this.getUsers = function () {
        $log.log(baseUrl);
        return $http.get(baseUrl);
    };
}]);

Create controller with dependency injection to set data to HTM or UI part.

// here '$scope', 'UserService' is dependency injection on controller
app.controller('myController', ['$scope', 'UserService', function ($scope, UserService) {
    // Function to fetch data
    $scope.getUserData = function () {
        UserService.getUsers()
        .then(function (response) {
            $scope.users = response.data; // return the response data 
        }, function (error) {
            console.error('Error fetching data:', error);
        });
    };
    // Call the function to fetch data on controller load
    $scope.getUserData();
}]); 

Create a custom filter for searching any keyword in the user list.

// create custom search filter like type any keyword in search box and display in the ui format
app.filter('customFilter', function () {
    return function (items, searchText) {
        if (!searchText) {
            return items;
        }
        searchText = searchText.toLowerCase();
        return items.filter(function (item) {
            return Object.keys(item).some(function (key) {
                if (typeof item[key] === 'object') {
                    return Object.keys(item[key]).some(function (subKey) {
                        return String(item[key][subKey]).toLowerCase().includes(searchText);
                    });
                }
                return String(item[key]).toLowerCase().includes(searchText);
            });
        });
    };
});

 

Step 3.

Bind all code in one file 

<!doctype html>
<html lang="en" data-ng-app="myApp">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AngularJS Todo List</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <!-- Angurr JS CDN  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"
        integrity="sha512-KZmyTq3PLx9EZl0RHShHQuXtrvdJ+m35tuOiwlcZfs/rE7NZv29ygNA8SFCkMXTnYZQK2OX0Gm2qKGfvWEtRXA=="
        crossorigin="anonymous" referrerpolicy="no-referrer">
        </script>
</head>

<body>
    <div class="container" ng-app="myApp" ng-controller="myController">
        <h2>Dependency injection and its importance example</h2>
        <hr>
        <div class="row g-3">
            <div class="col-12 ">
                <div class="d-flex flex-column flex-md-row justify-content-md-between">
                    <h1>Users List</h1>
                    <div>
                        <input type="search" data-ng-model="search" placeholder="Search user" class="form-control"
                            autofocus="true" />
                    </div>
                </div>
                <hr>
                <div class="row row-cols-1 row-cols-md-3 g-4">
                    <div class="w-100 py-3"
                        data-ng-if="(filteredUsers = (users | orderBy:'id':true | customFilter:search)).length == 0">
                        <div class="d-flex justify-content-center fw-bold">
                            <div class="text-center">
                                <p class=" fs-2 ">
                                    <span class="me-2">πŸ˜•</span>
                                    No records were found
                                </p>
                                <p class="fw-normal">try somthing new keywords</p>
                            </div>
                        </div>
                    </div>
                    <div class="col" data-ng-repeat="user in filteredUsers">
                        <div class="card h-100">
                            <div class="card-header bg-transparent border-success position-relative">
                                <span
                                    class="fw-bold px-2 position-absolute end-0 me-2 bg-black rounded-pill text-white">{{$index
                                    + 1}}</span>
                                <p class="d-flex flex-wrap m-0">
                                    <span class="bi bi-envelope me-1"></span>
                                    {{user.email}}
                                </p>
                            </div>
                            <div class="card-body">
                                <h5 class="card-title">{{user.name}}, <small
                                        class="text-black-50">({{user.username}})</small></h5>
                                <address class="card-text">
                                    <span data-ng-repeat="(key, value) in user.address" ng-if="key !== 'geo'">
                                        {{key}} - {{value}},
                                    </span>
                                </address>
                                <p class="mb-1"><span class="bi bi-globe me-1"></span><a
                                        href="https://www.{{user.website}}" target="_blank">{{user.website}}</a></p>
                                <p class="mb-1"><span
                                        class="bi bi-briefcase-fill me-1"></span><span>{{user.company.name}}</span></p>
                            </div>
                            <div class="card-footer">
                                <p class="mb-1"><span
                                        class="bi bi-phone-vibrate-fill me-1"></span><span>{{user.phone}}</span></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        var app = angular.module('myApp', []);
        // Service to handle HTTP requests
        app.service('UserService', ['$http', '$log', function ($http, $log) {
            var baseUrl = 'https://jsonplaceholder.typicode.com/users';

            this.getUsers = function () {
                $log.log(baseUrl);
                return $http.get(baseUrl);
            };
        }]);

        // here '$scope', 'UserService' is dependency injection on controller
        app.controller('myController', ['$scope', 'UserService', function ($scope, UserService) {
            // Function to fetch data
            $scope.getUserData = function () {
                UserService.getUsers()
                    .then(function (response) {
                        $scope.users = response.data; // return the response data 
                    }, function (error) {
                        console.error('Error fetching data:', error);
                    });
            };
            // Call the function to fetch data on controller load
            $scope.getUserData();
        }]);
        // create custom search filter like type any keyword in search box and display in the ui format
        app.filter('customFilter', function () {
            return function (items, searchText) {
                if (!searchText) {
                    return items;
                }
                searchText = searchText.toLowerCase();
                return items.filter(function (item) {
                    return Object.keys(item).some(function (key) {
                        if (typeof item[key] === 'object') {
                            return Object.keys(item[key]).some(function (subKey) {
                                return String(item[key][subKey]).toLowerCase().includes(searchText);
                            });
                        }
                        return String(item[key]).toLowerCase().includes(searchText);
                    });
                });
            };
        });
    </script>
</body>

</html>

 

Thank you.

I hope you are enjoying this article.

 

 


The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By