jforjs jforjs - 1 month ago 21
AngularJS Question

How to prove that angular services are singleton?

I heard that angular services are singleton. How can i prove that. For vanilla javascript, i can create a singleton pattern and prove it like the below code.



var mySingleton = (function(){
var instance;

function init(){
var privateRandomNumber = Math.random();
return {
getRandomNumber : function(){
return privateRandomNumber;
}
}
}
return {
getInstance: function(){
if(!instance) {
instance = init();
}

return instance;
}
}
})();

var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();

console.log(singleA.getRandomNumber() === singleB.getRandomNumber());





Can anyone give me a code snapshot to prove Angular Services are singleton like I am doing in above code.

Answer
var myApp = angular.module('myApp',[]);
myApp.service('mySingleton', function() {
    var privateRandomNumber = Math.random();
    return {
        Number : privateRandomNumber
    };
});

function MyCtrl($scope, mySingleton) {
    $scope.randNumber = mySingleton.Number;
}

function MyCtrl2($scope, mySingleton) {
    $scope.randNumber = mySingleton.Number;
}

HTML Code

<div ng-controller="MyCtrl">
   Hello, {{randNumber}}!
</div>
<div ng-controller="MyCtrl2">
   Hello, {{randNumber}}!
</div>

Yes, both the randNumber are same.

Comments