Services In AngularJS

In AngularJS a Service is a component that do some specific work not like other services we assume to be get from web server. Services in AngularJS do lot many other stuffs.

What Services in AngularJS do:
# Services provide the reusable logic.
# Simplify the code(controller) by putting some logic in the services.
# Create shared data/global data because services can only be instantiated once in an application. like
var app = angular.module(“Myapp”, []);
app.service(” XYZ”, xyz);  // Injects a global object (utility like logger, Error handler)

# Provide the test ability feature easy to do unit testing.
In Angular we are very much work on the principals of Dependency Injection (DI) i.e. the dependent objects are being injected rather than consumer creates. It’s impossible to work on AngularJS without DI.
DI provides the benefits of Decoupling and Testing to illustrate assume we have a Order class as below.
function Order($scope, $http, product)
$scope.Product = product;   // Here the product object gets added to the Order class  worry # Decoupling: not to worry about changes as being injected by other system. #Testing: on same principal for “$http” object we can mock a fake and inject it for testing offline.

There are built-in service components in AngualrJS…
$http– Service to grab data from web server. call HTTP methods GET.POST,PUT DELETE. $http service automatically convert a JSON response to JavaScript object.
etc..We can also create our own custom service.

There are 24 ways to register a service in AngularJS simplest one is the Factory..Can be registered as like below.

var MyServiceModule = angular.module(‘MyServiceModule’, []);
MyServiceModule.factory(‘MyWebAPIService’, [‘$http’, function ($http) {

var urlBase = ‘http://localhost:57856/api’;
var MyWebAPIService = {};

MyWebAPIService.getItems = function () {
return $http.get(urlBase + ‘/products’);
return MyWebAPIService;

Here we are using the build in “$http” service component to call a REST API and return the data/model.

** “Factory” and “Service” are way of doing DI in angularJS. Factory does not create a instance it just pass the method.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s