Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another.

The error message I'm getting is:

  `ReferenceError: testDataService is not defined`

I thought it would be a simple issue to resolve, but it's turning out to be quite challenging. It seems like I'm struggling with the syntax related to dependency injection.

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

   this.treeGridOptions = gadgetInitService.initTreeGridTEST();

Everything looks good up to this point.

However, the problem arises below in initTreeGridTEST

Here's my implementation of the testDataService factory, which just provides 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 here's where 'testDataService' is being injected:

 (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;
}
})();

Any help or advice on this matter would be greatly appreciated,

Bob

Answer №1

testDataService is a variable within the scope of function gridHierarchyService. Accessing it outside the function where it is defined will result in an error. To resolve this, simply move the function initTreeGridTEST inside the factory constructor.

(function () {
'use strict';

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

//Using string notation for dependency injection
gridHierarchyService.$inject = ['testDataService'];

function gridHierarchyService(testDataService) {
//Storing service object in a variable if needed for referring public functions
 return { 
    initTreeGrid: _initTreeGrid,
    initColumnChart: _initColumnChart,
    initTreeGridTEST: _initTreeGridTEST
 }

 function _initTreeGridTEST() {
   var myData = testDataService.treegridData();
   return myData;
 }

}

})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the advantages of using React JS for a Single Page Application compared to server-side rendering?

Currently, I am faced with a conundrum when it comes to selecting the best approach for a highly scalable project. On one hand, server-side rendering using Node.js with Express (utilizing EJS) to render full HTML pages is an option. On the other hand, ther ...

Refresh a DIV using two SQL queries in forms

I am encountering an issue with updating a single div element using the results from two different forms on an HTML page. I want either form1 or form2 to display results in the same div element, and it should be updated with one line of content fetched fro ...

Drawing a line beneath the mouse's center using JavaScript

Struggling with my JavaScript drawing tool, particularly the draw() function. The line is consistently off-center below the mouse cursor. How do I fix this issue? My aim is to have the line always follow the center of the mouse as it moves. Could someone c ...

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Preloading Vue dynamic routes for optimal performance

Currently dealing with a challenge on my Vue project and could use some help. I'm looking to prerender specific dynamic routes when I navigate to a particular route within the application. On the /works route, there's a list of items displa ...

Tips for retrieving a local variable from inside a callback and using it outside the function

Recently, I started utilizing npm plaid and I'm looking for a way to access the variable trans outside of the plaidClient.getTransactions function. Any suggestions would be greatly appreciated. var trans; var startDate = moment().subtract(30, &apo ...

JavaScript Asynchronous Functions Not Handling Await Calls Correctly

The two fadeInList functions control the fading animation of a continuous list split into two lines. The typeOutText function displays text and is supposed to execute List1 first, wait for it to finish, and then proceed with List2. However, after adding ke ...

Tips for incorporating fading text and a CTA into your content block

I am looking to protect the full content of my blog posts and allow access only to subscribed members. I want readers to see just a glimpse of the article before it disappears, prompting them to take action with a Call to Action (CTA) like in the fading te ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

AJV is failing to validate my body using the function generated by the compile method

Currently, in my API development process with express, I have implemented AJV as a middleware to validate the incoming body data. The version of AJV being used is 6.12.6 Below is the JSON schema named body-foobar.json: { "type": "object& ...

What is the best way to create a reactive prop within this Vue 3 application?

I've been developing a news application using Vue 3 along with the News API. My current focus is on implementing a search feature. Within my App.vue file, I have: <template> <TopBar @search="doSearch" /> <div class=" ...

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

Implementing a restricted Mongoose promise loop iteration count

Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check i ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

Add owl carousel to your npm project in any way you see fit

After struggling for a while, I finally wanted to implement owl-carousel, but couldn't figure out how to connect it using npm and webpack. The official NPM website states: Add jQuery via the "webpack.ProvidePlugin" to your webpack configuration: ...

Searching for hidden elements within a div using a filter option

An accordion is located inside a div and a search box has been added to the div with the intention of serving as a search filter. Some accordion elements are visible within the div while others are hidden. The problem arises when trying to make the filter ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...