4.5.14

AngularJS: dummy guide for service, factory, provider, configuration

Resources:
Angular.js: service vs provider vs factory?
AngularJS Factory, Service and Provider
Understanding Service Types
Angular Constants, Values, Factories, Services, Providers and Decorators, Oh My!

Providers (docs)
$provide (docs)

Summary of below explanation

After writing below explanation I found out that I just need very short summary for each time I write service or factory.

General Idea

  • Service / Factory / Provider are ways to define singletons in angularJS application. they are injected when asked for.
  • When they are defined, they are given (1) name and (2) function.
  • Service and Factory are suger function that convert their input to providers.

Usage:

  • Value injected for service - instance of the service function.
  • Value injected for factory - return value of factory function.
  • Value injected for provider
    • In config phase - instance of provider function.
    • In run phase - return value of $get() of provider function.

Overview

All Services are singletons, they get instantiated once per app. If we modify foo.variable in one place, the other places will have that change too, it does not matter if factory or service or provider is used.

The factory, service and provider methods are all functions. They teach the Injector how to instantiate the Services.

Services or Factories don't exist in Angular as distinct constructs, there are only providers and the instances they produce. The service() and factory() functions on Module are just convenience functions that accept functions or instances and turn them into providers, they don't represent any special Angular constructs by those names. 

Factory

Example:
angular.module('mod1').factory('nameOfFactory', 
        function (requiredService1, requiredService2) {
        var v1 = 'value';
        var v2 = 'value2';
       
    
        var func1 = function (args) {
           
        };

        var func2 = function (args) {
           
        };
        
        return {
            func1: func1,
            func2: function () {..logic..},
            const: 'VALUE'
        };
    });

What is returned on injection:
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

The Service way is almost the same as the Factory way, but in Service way, the Injector invokes a constructor with the new operator instead of a factory function.

Factory allows us to add some logic before creating the object we require.Provider is the most configurable of all three.  All other providers are derived from it. It enables us define how the service will be provided even before the injection system is in place. This is achieved with configure call where we register work during the modules configuration phase.

Usage:
Could be useful for returning a 'class' function that can then be new'ed to create instances.

How can be used?
This means that you can use any field of the object. Example: nameOfFactory.func1();

From angular.js
function factory(name, factoryFn) { 
   return provider(name, { 
      $get: factoryFn }
      ); 
}

Service

Example:
angular.module('mod1').service('nameOfService', 
        function (requiredService1, requiredService2) {
        var v1 = 'value';
        var v2 = 'value2';
        ..logic..
    
        this.func1 = function (args) {
            ..logic..
        };

        this.func2 = function (args) {
            ..logic..
        };
    });


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

The Service way is almost the same as the Factory way, but in Service way, the Injector invokes a constructor with the new operator instead of a factory function.

When you use it for the first time, it will do a new Foo(); to instantiate the object. Keep in mind that it will return the same object if you use this service again in other places.

Usage
Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. 

Service is suitable for cases when you have a ready function that you need to share throughout the app without any “preprocessing”.

How can be used?
This means that you can use any function that is defined on this of the service and state of service will be local to each usage of it. Example: nameOfService.func1();

From angular.js

function service(name, constructor) {

    return factory(name, ['$injector', function($injector) {

      return $injector.instantiate(constructor);

    }]);

  }

Providers

Example:

angular.module('mod1').provider('nameOfProvider', / without 'Provider' postfix

        function (requiredService1, requiredService2) {

        var v1 = 'value';

        var v2 = 'value2';

       
    
        this.func1 = function (args) {
           
        };

        this.func2 = function (args) {
           
        };
        
        this.$get = function (args) { 
            ...logic...
            
            return {
                func1: func1,
                func2: function () {..logic..},
                const: 'VALUE'
                };
            };
    });

What is returned on injection:
When declaring providerName as an injectable argument you will be provided with ProviderFunction().$get().

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

Provider is the most configurable of all three.  All other providers (factory, service) are derived from it. It enables us define how the service will be provided even before the injection system is in place. This is achieved with configure call where we register work during the modules configuration phase.

How can be used?
Use the provider in configuration phase of the module to call functions of the provider to define how it should work.

In the run phase, use the functions from the returned object from $get.


3 comments:

digital signature software said...

I just want to thank you for the work that you do and your willingness to share. You have created outstanding materials and we all benefit from your generosity.

Qa Tools said...

It was so nice article.I was really satisified by seeing this article and we are also giving QA online training.The QA online training is one of the best QA online training institute in USA.

Michale Daniel said...

it was really a nice article and i was really impressed by reading this
article We are also giving Linux Course Online Training.the Linux-
-Online-Training
is the one of the best Online Training institute.