Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare AngularJS service multiple times in the same module

I am working with AngularJS 1.x and I can define the same service multiple times in the same module. In the following snippet of code, I am defining the service nameService 2 times in module myApp:

(function() {
  'use strict';

  angular
    .module('myApp', [])
    .controller('MainController', MainController)
    .factory('nameService', nameService1)
    .factory('nameService', nameService2);

  MainController.$inject = ['nameService'];

  function MainController(nameService) {
    var vm = this;

    vm.message = nameService.getName();
  }

  function nameService1() {
    return {
      getName: getName
    };

    function getName() {
      return 'First Definition';
    }
  }

  function nameService2() {
    return {
      getName: getName
    };

    function getName() {
      return 'Second Definition';
    }
  }
})();

At runtime, AngularJS will use the value returned by the second implementation of the service: "Second Definition". Please check the this Plunker example.

So, empirically, AngularJS seems to use always the latest definition of a service, ignoring the previous ones.

My question is: is there any official documentation describing this behavior?

like image 231
Andrea Avatar asked Oct 26 '16 09:10

Andrea


2 Answers

Here, you are overwriting definition of factory/service. factory/service is singleton i.e. there will be only one instance of it.

factory('name', constructing_function)

Your case,

factory('nameService', nameService1)//Here object { getName: getName } will be assigned to nameService instance.

factory('nameService', nameService2)//Here object { getName: getName } (#2nd definition) will be assigned to nameService instance. i.e. nameservice instance referring to (#2nd definition).
like image 179
ram1993 Avatar answered Sep 17 '22 01:09

ram1993


That's the way how JavaScript works:

function Vinoth(){console.log("Printing first")}

function Something(){console.log("Printing Something")}

function Vinoth(){console.log("Printing Second")}

When you do a console.log(Vinoth());, it would always print the Second one. Over to your second part:

  angular
    .module('myApp', [])
    .controller('MainController', MainController)
    .factory('nameService', nameService1)
    .factory('nameService', nameService2);

AngularJS services are singleton by nature, so its going to be one instance across your application life cycle. Your nameService1 and nameService2 are pointing to same nameService instance. Technically it nameService holds nameService2 as it precedes according to hoisting.

like image 25
Thalaivar Avatar answered Sep 21 '22 01:09

Thalaivar