Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Medium

AngularJs Services

gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

AngularJs is a framework based on Javascript developed by Google to create web applications. AngularJs is an open-source framework that developers primarily use to build dynamic websites or web applications. The main reasons it is famous as a framework are its built-in services or modules and code reusability in the application.

AngularJs service introduction image

In this blog, we will talk about AngularJS services, both built-in and custom services that promote code reusability in the application, and we will learn how to implement these services with a few examples.

What is AngularJS Services?

AngularJS Service is a method or object used to create variables/data that we can use outside the components in which it is explained. 

Let's compare the AngularJS services with a real-life example; food delivery services are available in our society, so we don't have to go to the shops and order food. We can order online, and it saves us effort and time. You can think of AngularJS services as the same because there are services we can use in the application that saves us the time and effort of writing the functionality or code.

AngularJS has various built-in services we can use according to our needs, and we can also create our services if we want to add some functionality as service in our application. We will learn how to use built-in services and also how we can make our custom services in AngularJs.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Need of Services

One of the reasons to use services in AngularJS is to promote code reusability and organization of the code. Assume there is a service you want to implement in different application components.

There are better approaches to creating separate module files for components in this scenario. We can use just one common service we can integrate whenever we need it in the application.

Now let's implement the AngularJS built-in services and create a custom service for better understanding.

Types of Services

Types of Services

This article will discuss a few built-in services offered by angular. The built-in services that we are going to implement are the ones that are commonly used during development.

$parse

This service converts a regular expression into an appropriate function. 

$rootScope

 This service provides a root scope for a variable, or we can say that it allows for a global scope for the variable. 

$http

With the help of the $http service, we can use HTTP requests like GET, PUT, POST, and many more in the application. We use HTTP requests to connect with servers. Let's consider an example to understand.

Example

Links.json file

{
	"Coding Ninjas Studio": [{
		"name":"AngularJS includes",
		"link":"https://www.codingninjas.com/studio/library/angularjs-includes"
	},
	{
		"name":"AngularJS Events",
		"link":"https://www.codingninjas.com/studio/library/angularjs-events"
	},
	{
		"name":"AngularJS Forms",
		"link":"https://www.codingninjas.com/studio/library/angularjs-forms"
	}]
}


Index.html file

<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
    </head>
    <body>
        <div>
            <h1>Resources for AngularJS</h1>
            <table border="2">
                <thead>
                    <th>Blog Name</th>
                    <th>Blog link</th>
                </thead>
                <tbody>
                    <tr ng-repeat="url in data">
                        <td>{{url.name}}</td>
                        <td>{{url.link}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($http, $scope) {
                $http.get('links.json').then(function(res) {
                    $scope.data = res.data.Coding Ninjas Studio;
                }).catch(function(err) {
                    console.error(err);
                });
            });
        </script>
    </body>
</html>


OUTPUT

HTTP service output

$timeout

This service is for setting up a delay in the execution of a function. For example, if you want to add a popup on the page, but it should be executed after it is loaded, then you can use the $timeout service. This service is similar to the Javascript timeout function. Let's see an example to understand it better.

Example

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="timeout-Controller">
        <div>
            <h2>Wait for 5 Seconds </h2>
            <h1>{{greetings}}</h1>
        </div>
        <script>
            var timeoutScript = angular.module('myApp', []);
            timeoutScript.controller('timeout-Controller', function($scope, $timeout) {
                $timeout(function() {
                    $scope.greetings = "Hey! Welcome to Coding Ninjas";
                }, 5000);
            });
        </script>
    </body>
</html>


OUTPUT

timeout service output


After 5 seconds, we get the ‘greetings’ as defined in the code above.

service after timeout output

$interval

This server is an angular wrapper version of windows.setInterval of Javascript. When you want to execute a function or module after some fixed interval or time, then you must use the $interval service in your application. Let's observe an example to understand better.

Example

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    </head>
    <body>
        <div ng-app="myApp" ng-controller="interval-ctrl">
            <h2>You will see a reminder every 6 seconds</h2>
        </div>
        <script>
            var app = angular.module('myApp', []);
            app.controller('interval-ctrl', function($scope, $interval) {
                $scope.reminder = alert('This a reminder to Turnoff the Gas!');
                $interval(function() {
                    $scope.reminder = alert('This a reminder to Turnoff the Gas!');
                }, 6000);
            });
        </script>
    </body>
</html>


OUTPUT

interval service output

After every 6 seconds, we will get a reminder like this:

interval service reminder output

We have covered most of the essential services if you are working on AngularJS application development. But there are more services which might be helpful to you. For other services, you can go to the official documentation of AngularJS.

Create Custom Service

After inbuilt service implementation, it is time to implement custom services. Custom services are an essential part of AngularJS applications. They let us create our service with specific functionality. AngularJS allows us to develop services we can connect to our module. Then we can use that service in our application in various components if required.

In the following example, we will convert rupees into USD with a custom service app.service("conversion", function(){ }) in our code.

Example

<!DOCTYPE html>
<html ng-app="myApp" ng-controller="custom-service">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    </head>
    
    <body>
        <h1>Convert Rupees into USD$</h1>
        
        <div>
            <input type="text" ng-model="data" placeholder="Enter your amount">
            </br>
            <button ng-click="sendData(data)">Click Me</button>
            <p>This Value is ${{numb}}</p>
        </div>
        
        <script>
            var app = angular.module("myApp", []);
            
            // Custom Service
            app.service("conversion", function() {
                this.serviceFun = function(value) {
                    return value / 82;
                }
            })
            app.controller("custom-service", function($scope, conversion) {
                $scope.sendData = function(data) {
                    $scope.numb = conversion.serviceFun(data);
                    console.log($scope.numb);
                }
            });
        </script>
    </body>
</html>


OUTPUT

custom service output

Frequently Asked Questions

What is AngularJS Services?

AngularJs Service is a method or object used to create variables/data that we can use outside the components in which it is explained.

Why do we need AngularJS services?

Services in AngularJS are to promote code reusability and organization of the code.

AngularJS Services depends on which mechanism?

These services are injectable, which follows the dependency injection mechanism. 

Is AngularJS a framework or library?

AngularJs is an open-source framework that developers primarily use to build dynamic websites or web applications.

Can we create our custom service in AngularJS?

Yes, we can create custom services in AngularJS and use them in our application.

Conclusion

In this blog, we discussed AngularJS services. We have covered both built-in and custom services. We have also implemented examples with codes and output for better understanding.

To learn more about AngularJS, you can check out the following articles.

To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

Happy Coding!

Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass