Unit 3
Angular Services
Akshata S Bhayyar
Assistant Professor,
Dept. of CSE, RIT
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Content
• Overview of the built-in AngularJS services,
• understanding services and dependency injection
• Creating custom services Implementing services in controllers using angular's
$http and $resource services, Promises,
• Service registration and injection,
• using services to build a service, injecting services,
• Build: Create a Twitter search service: Submit simple search, Set result size.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Download XAMPP to run $http services
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
AngularJS Services
What is a Service?
In AngularJS, a service is a function, or object, that is available for, and limited to,
your AngularJS application.
AngularJS has about 30 built-in services.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
AngularJS Services
▪ One of them is the $location service.
▪ The $location service has methods that return
information about the location of the current web page:
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Why use Services?
• For many services, like the $location service, it seems like you could
use objects that are already in the DOM, like the [Link]
object, and you could, but it would have some limitations, at least for
your AngularJS application.
• AngularJS constantly supervises your application, and for it to handle
changes and events properly, AngularJS prefers that you use the
$location service instead of the [Link] object.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
List of few of Angular JS services
• Here are some of the most commonly used built-in services in AngularJS:
1. $http
• Used for making HTTP requests (GET, POST, PUT, DELETE, etc.).
2. $resource
Provides an easy way to interact with RESTful APIs. Requires ngResource
module.
RESTful API (Representational State Transfer Application Programming Interface)
3. $q
• Helps in handling promises for asynchronous operations.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
List of Angular JS services
4. $timeout
• Executes a function after a specified delay.
5. $interval
• Executes a function at regular intervals.
6. $location
• Provides URL manipulation features.
7. $window
Provides access to the browser's window object.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
List of Angular JS services
8. $document
Provides access to the document object.
9. $log
Wrapper around [Link], [Link], etc.
10. $filter
• Applies filters to data.
11. $parse
• Converts AngularJS expressions into functions.
12. $compile
• Compiles HTML strings or DOM elements into AngularJS templates.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
List of Angular JS services
13. $rootScope
• The parent scope of all AngularJS applications.
14. $scope
• A special object that binds views and controllers.
15. $animate
(requires ngAnimate)Provides animation support.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
The $http Service
• The $http service is one of the most common used services in
AngularJS applications. The service makes a request to the server, and
lets your application handle the response.
• $http is an AngularJS service for reading data from
remote servers.
• he AngularJS $http service makes a request to the server, and returns
a response.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
The $http Service
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Output
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
The $http Service
• Steps
1. Download xampp server
2. Start server
3. Create project folder in the htdocs folder of xampp
1. Place HTML file and message file ([Link])
2. open browser and type
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
$timeout
• The $timeout service is AngularJS' version of the [Link]
function.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
$timeout
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
$interval
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Creating Services
• Application developers are free to define their services by
registering the service's name and service factory function,
with an AngularJS module.
• The service factory function generates the single object or
function that represents the service to the rest of the
application.
• The object or function returned by the service is injected into
any component (controller, service, filter or directive) that
specifies a dependency on the service.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Registering Services
• Services are registered to modules via the Module API.
Typically you use the Module factory API to register a service:
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Registering Services
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
RESTful APIs
• RESTful APIs (short for Representational State Transfer APIs) are web
services that follow the REST architecture to allow communication
between client and server over HTTP.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
RESTful APIs
Concept Explanation
Client The app or browser that makes requests
The system that handles requests and sends
Server
responses
Resource A piece of data, like a user, post, or product
A specific URL used to access a resource (e.g.,
Endpoint
/api/users)
HTTP
Define actions: GET, POST, PUT, DELETE
methods
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
HTTP Methods in REST
Method Description Example URL
GET Read data GET /api/users
POST Create new data POST /api/users
Update existing
PUT PUT /api/users/123
data
DELETE Delete data DELETE /api/users/123
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Example: RESTful API for "Users"
Action HTTP Method URL Description
Get all users GET /api/users Returns list of users
Get a user by ID GET /api/users/1 Returns user with ID 1
create a new
POST /api/users Adds a new user
user
Update a user PUT /api/users/1 Updates user with ID 1
Delete a user DELETE /api/users/1 Deletes user with ID 1
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
$resource : Setup
✓$resource is a separate, optional module of AngularJS, built over $http.
✓It allows to create a javascript object that represents the data model.
✓In this way each operation computed on the object created through
$resource, is performed also on the server.
✓$resource should be used instead of $http each time the web
application has to deal with a Restful web service.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
$resource : Setup
1. First, include the ngResource module in your app:
2. And declare the module dependency:
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="[Link]
<script src="[Link]
</head>
<body ng-controller="MainCtrl">
<h3>Posts:</h3>
<ul>
<li ng-repeat="post in posts">{{ [Link] }}</li>
</ul>
<script>
[Link]('myApp', ['ngResource'])
.controller('MainCtrl', function($scope, $resource) {
var Post = $resource('[Link]
$[Link] = [Link](); // GET all posts
});
</script>
</body>
</html>
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
To add a user
To modify your current AngularJS code to add a user,
we’ll add the following:
✓Uses ng-model="[Link]" for input.
✓Submits the username with a POST request to the API.
✓On success, adds the new username to $[Link] immediately.
✓Uses a simulated id since JSONPlaceholder doesn't save real data.
1. Programs\[Link]
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
To Delete a user
•List users
•Add a user (username only)
•Delete a user from the list immediately
Programs\[Link]
•[Link]({ id: [Link] }) sends a DELETE request to the mock API.
•The user is then removed from the $[Link] list.
•This reflects deletion immediately in the UI even though the backend
(jsonplaceholder) doesn’t actually remove anything.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
update a user's username.
•List users
•Add a new user
•Delete a user
•Update a user’s username
Programs\[Link]
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Promises
• A Promise is an object that represents the eventual result (or failure) of an
asynchronous operation, such as an HTTP request.
• Promises are provided by AngularJS's $q service and are used heavily in
services like $http and $resource.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
States of a Promise
•Pending – the async operation is still in progress.
•Resolved (Fulfilled) – the operation completed successfully.
•Rejected – the operation failed.
•Allow chaining .then() for success and .catch() for errors.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
States of a Promise
<!DOCTYPE html>
<html ng-app="promiseApp">
<head>
<script src="[Link]
</head>
<body ng-controller="MainCtrl">
<h3>Data from API:</h3>
<div>{{ data }}</div>
<script>
[Link]('promiseApp', [])
.controller('MainCtrl', function($scope, $http) {
$[Link]('[Link]
.then(function(response) {
// Promise resolved
$[Link] = [Link];
})
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
States of a Promise
.catch(function(error) {
// Promise rejected
$[Link] = 'Error loading data';
});
});
</script>
</body>
</html>
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
States of a Promise
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Custom $q Promise Example
<!DOCTYPE html>
<html ng-app="promiseApp">
<head>
<meta charset="UTF-8">
<title>AngularJS $q Promise Example</title>
<script src="[Link]
</head>
<body ng-controller="MainCtrl">
<h2>Custom $q Promise Example</h2>
<label>Enter Name: </label>
<input type="text" ng-model="userName">
<button ng-click="greetUser()">Greet</button>
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Custom $q Promise Example
<p><strong>Result:</strong> {{ message }}</p>
<script>
[Link]('promiseApp', [])
.controller('MainCtrl', function($scope, $q, $timeout) {
function asyncGreeting(name) {
var deferred = $[Link]();
$timeout(function() {
if (name) {
[Link]("Hello, " + name + "!");
} else {
[Link]("Error: No name provided.");
}
}, 1000); // Simulate delay
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Custom $q Promise Example
return [Link];
}
$[Link] = function() {
$[Link] = "Processing...";
asyncGreeting($[Link])
.then(function(greeting) {
$[Link] = greeting;
})
.catch(function(error) {
$[Link] = error;
});
};
});
</script>
</body>
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
</html>
Dependency Injection (DI) in AngularJS
• It is a software design pattern that deals with how
components get hold of their dependencies.
• In AngularJS, it allows you to inject services, factories,
or values into your components (like controllers,
directives, filters, etc.), promoting loose coupling and
easier testing.
• Instead of creating dependencies manually within a
component, you "inject" them when the component is
instantiated. This makes the component easier to test
and reuse.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Why Use Dependency Injection?
• Improves modularity.
• Easier unit testing (you can mock dependencies).
• Reusability and maintainability.
• Decouples components from their dependencies
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
How AngularJS Dependency Injection
Works
AngularJS has a built-in injector that is responsible for creating and injecting
dependencies.
Dependencies can be:
• Services
• Factories
• Values
• Constants
• Providers
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
How AngularJS Dependency Injection
Example
• AngularJS module: myApp
• GreetService: a custom service that returns a greeting message.
• MainController: a controller that injects GreetService using array-style
dependency injection (safe for minification).
• HTML uses AngularJS expressions ({{ message }}) to display the output.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Step-by-Step: Build a Service Using
.service()
1. Define the AngularJS Module
2. Create a Service Using .service() : The .service() method defines a constructor
function that AngularJS will use with the new keyword.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Step-by-Step: Build a Service Using
.service()
3. Use the Service in a Controller : You can inject MathService into any controller:
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Example : Summary
• Use .service() to define a reusable service.
• Services are singletons – they’re shared across the app.
• Inject them into controllers, directives, filters, etc.
• Ideal for business logic, data access, utility functions.
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Twitter search service using AngularJS
in HTML
Prerequisites
• Twitter API v2 Bearer Token (if using real Twitter
API)
• AngularJS library
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT
Akshata S Bhayyar,Assistant Professor, Dept. of CSE, RIT