Tuesday 28 March 2017

What is Services and Factory in AngularJS



Services are singleton objects. In other words, It's javascript function to perform a specific task. Angular allow us to use these services with controllers, service, filter or directive.

Whenever we want to use service with the above components, we will have to inject the service name along with the component. By doing so, component ask angular to load that particular service in the application. This method of injecting service is called dependency injection.

To know more about the complete collection of Service lists, please visit Complete lists of Services.


To use a service, you will have to add it as a dependency with a component  such as controller, filter  or service. To add a service with component, you have to pass it as an argument.

For Example:

App.controller(“controllerName”, function($scope, $service))
{

});

In the above example we injected our $service along with the controller.


There are 2 types of Services are available in AngulrJS,

1.     Inbuilt Service
2.     Custom Service

Inbuilt Service:

AngulaeJS provides  many Built-in Services and Each service has individual functions and characteristics. The built-it services are prefixed by $ sign.


For Example,

$http, $filter, $route, etc.,

Custom Services:

AngularJS allows users to create their own Service. You can add any functions and behaviors to the custom service.

For Example,

app.service('servicename', function() {

this.maethodname1 = function() {
......
}
this.methodname2 = function() {
......
}

});


In the factory method of creating service, we first create empty object of the factory then we assign properties and method to it and at last, we return the factory object. Below syntax is used to create service using factory method.

For Example,

modulename.factory('Factoryname', function() {
var factory = {};
factory.methodname1 = function() {
.............
}
factory.methodname2 = function() {
..............
}
return factory;
});
We can also inject the above existing factory in to our service.

For Example,

app.service('servicename', function(‘'Factoryname'’) {

this.maethodname1 = function() {
......
}
this.methodname2 = function() {
......
}

});

I hope you got a cleared information about service and Factory. To know more about all other topics, please visit AngularJS Complete Topics.