AngularJS: Service vs provider vs factory

services vs provider vs factory


Services

Services are singletons, which are objects that are instantiated only once per app (by the $injector). They provide an interface to keep together methods that relate to a specific function.

The $http service, for instance, is an example of an AngularJS service, as we saw in the last article. It provides low-level access to the browser’s XMLHttpRequest object. Rather than needing to dirty the application with low-level calls to the XMLHttpRequest object, we can simply interact with the $http API.

Angular comes with several built-in services with which we’ll interact consistently. It will also be useful to make our own services for any decently complex application.

AngularJS makes it very easy to create our own services, simply by registering the service. Once a service is registered, the Angular compiler can reference it and load it as a dependency for runtime use.

Here is the simplest, most common way to create a service, by using the angular.module API factory:

There are two ways to create a service.

      1. factory
      2. service

Syntax: module.service( 'serviceName', function );

Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Example Code:

   mainApp.service('CalcService', function(MathService){
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});

Factories

A factory is a simple function which allows you to add some logic before creating the object. It returns the created object.

Syntax: module.factory( 'factoryName', function );

app.factory('serviceName',function(){ return serviceObj;})

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Example Code:

var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
   var factory = {};
  
   factory.multiply = function(a, b) {
      return a * b
   }
  
   return factory;
});

Providers

Syntax: module.provider( 'providerName', function );

Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.

Providers have the advantage that they can be configured during the module configuration phase.



AngularJS: Service vs provider vs factory Dev2Tricks 5 of 5
Services Services are singletons, which are objects that are instantiated only once per app (by the $injector). They provid...

Share this

Related Posts

Previous
Next Post »