Skip to main content

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.


Comments

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.

Popular posts from this blog

Best freeware - XML editor

As a software developer, I open XML files all the time. I a heavy commercial XML editor. But nothing can compare to a small, thin and free XML editor like 'foxe'. A great feature is has is the alignment of long XML strings to readable XML format (Shift-F8). It help lot of times when the XML file was generated by some tool and was not readable. Homepage: http://www.firstobject.com/dn_editor.htm

Jenkins error: groovy.lang.MissingPropertyException

I tried to run groovy build step and got below error. This post will describe how I solved the problem. Caught: groovy.lang.MissingPropertyException: No such property: hudson for class: script

SSL in pictures

Here is my summary on SSL (or as I like to call it 'SSL for dummies')