Search code examples
javascriptangularjsangularjs-service

Injecting an Angular factory into another factory


I'm having a bit of trouble getting a factory injected into another factory.

The error is:

  `ReferenceError: testDataService is not defined`

I thought it should be pretty easy to solve, but it's giving me a headache. I seem to have issues with the various syntax involved in dependency injection.

In my main factory, I'm making the initial service call like this :

   this.treeGridOptions = gadgetInitService.initTreeGridTEST();

Good so far.

However, further below it blows up in initTreeGridTEST

Here's my testDataService factory, which just returns some hard-coded options:

 (function () {
'use strict';
angular.module('rage').factory('testDataService', [testData ]);

function testData() {
    var service = {
        treegridData: treegridData
    };
    return service;
}
function treegridData() {
    return {
        "altrows": true,
        "sortable": true,
        "columnsResize": true,
        "editable": true,
        "showToolbar": false,
        "width": "100%",
        "height": 400,
        "source": {}       
    };
}   
})();

and trying to inject 'testDataService' here:

 (function () {
'use strict';

angular.module('rage').factory('gadgetInitService', ['testDataService', gridHierarchyService]);

function gridHierarchyService(testDataService) {
    var service = {
        initTreeGrid: initTreeGrid,
        initColumnChart: initColumnChart,
        initTreeGridTEST: initTreeGridTEST
    }
    return service;
}
function initTreeGridTEST() {
    var myData = testDataService.treegridData();
    return myData;
}
})();

Your help appreciated,

Bob


Solution

  • testDataService is just a variable in the scope of function gridHierarchyService and you are trying to access it outside the function where it is defined. Just move the function initTreeGridTEST inside the factory constructor and you should be good.

     (function () {
    'use strict';
    
        angular.module('rage').factory('gadgetInitService',gridHierarchyService);
    
        //Just used it instead of array notation, i prefer this since this is more readable
        gridHierarchyService.$inject = ['testDataService'];
    
        function gridHierarchyService(testDataService) {
        //yeah keep service it in a variable incase you need to use service object for referring public functions as is. I am just returning it.
         return { 
            initTreeGrid: _initTreeGrid,
            initColumnChart: _initColumnChart,
            initTreeGridTEST: _initTreeGridTEST
         }
    
         function _initTreeGridTEST() {
           var myData = testDataService.treegridData();
           return myData;
         }
    
       }
    
    })();