Setting up a service in angularjs that is reliant on another service

One thing I'm trying to figure out is how to utilize a service like $http outside of the $get function. Is this even possible? Currently, my code loads a json file that contains a dictionary used by my application in various ways. I want users to have the ability to customize this dictionary, so I'm using jQuery's extend method to allow them to add values and extend the dictionary. The instantiate method within the following code handles all of this. My goal is to configure my service as follows:

config(['_sys_dictionaryProvider', function(_sys_dictionaryProvider) {
    _sys_dictionaryProvider.instansiate('config/dictionary/custom/dictionary.json');
}])

However, this setup requires the $http service to be accessible during configuration, which I believe is not the case. If I include the $http service as part of the $get property, it will work (as mentioned here), but this means the network needs to be queried every time the service is used. Is there any way to use a service in the configuration of another service?

Below is the full code, please let me know if further clarification is needed.

app.provider("_sys_dictionary", ['$http',
    function ($http) {
        var dictionary,
            DictionaryService = function () {
                this.definitions = dictionary;
                this.define = function (what) {
                    var definitions = this.definitions;
                    if (what instanceof Array) {
                        for (var i = 0; i < what.length; i++) {
                            definitions = definitions[what[i]];
                        }
                        return definitions;
                    }
                    return this.definitions[what];
                };
            };
        return {
            $get: function () {
                return new DictionaryService();
            },
            instansiate: function (path) {
                $http.get('config/dictionary/dictionary.json').success(function (data) {
                    dictionary = data;
                    $http.get(path).success(function (data) {
                        jQuery.extend(true, dictionary, data)
                    });
                });
            }
        };
    }
]);

Answer №1

Being uncertain about the feasibility of using a service during the configuration stage, where the certainty of the service's own configuration is not guaranteed, I opted for an alternative approach

app.provider("_sys_dictionary", function () {
    var dictionary,
        DictionaryService = function () {
            this.definitions = dictionary;
            this.define = function (what) {
                var definitions = this.definitions;
                if (what instanceof Array) {
                    for (var i = 0; i < what.length; i++) {
                        definitions = definitions[what[i]];
                    }
                    return definitions;
                }
                return this.definitions[what];
            };
        };
    return {
        $get: [
            function () {
                console.log(dictionary);
                return new DictionaryService();
            }
        ],
        instansiate: function (path) {
            jQuery.ajax({
                url: 'config/dictionary/dictionary.json',
                success: function (data) {
                    dictionary = data;
                    jQuery.ajax({
                        url: path,
                        success: function (data) {
                            jQuery.extend(true, dictionary, data);
                        },
                        async: false
                    });
                },
                async: false
            });
        }
    };
});

Utilizing JQuery's AJAX object and setting async to false became my solution in ensuring the dictionary is prepared before its use in the service. Hopefully, this method proves useful to others. Any better alternatives are welcome!

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

Verify the status of the mongodb server synchronously

Is there a method to detect if a mongod instance is still operational while using mongoclient? In my mongoclient module, I have implemented a db.on('close') handler which functions properly when mongod exits normally. However, if the server proc ...

Designing Interactive Circular Dates on Website

Currently, I am working on a webpage using HTML, CSS, JavaScript, and PHP. The goal is to design a page that features 7 circles representing the current date and the next 6 days. Users should be able to click an arrow to navigate to the following 7 days. ...

React app experiencing crashes due to Material UI Select component issues

I am facing a challenge while trying to incorporate a material ui select component into the React application I am currently developing. Whenever I attempt to add a select functionality to a form, it results in a crash. Despite following the example provid ...

The AngularJS directive fails to load in the unit test environment

Here is the Karma configuration I am using: options: { browsers: ['PhantomJS'], frameworks: ['jasmine'], plugins: [ 'karma-jasmine', 'karma-phantomjs-launcher' ], reporters: &ap ...

Prevent the countdown timer from resetting every time I refresh the page

Whenever I refresh my page, the timer starts over. I want it to pick up from where it left off until it reaches 0. This is my JavaScript code for handling the timer: var target_date = new Date().getTime() + (1000*3600*48); // set the countdown date var ...

retrieving information from server via ajax to display on chart

I am currently utilizing the jqPlot JavaScript library for generating graphs and charts in one of my applications, which can be found at . Within my application, there are approximately 5-6 pages where I have integrated this library. However, I would like ...

The final condition of the ternary operator fails to render if the specified condition is satisfied

Having trouble identifying the issue with this ternary statement. The last element (blurredscreen) is not appearing when authStatus !== "authenticated". return ( <> <div key={"key-" + id}> {isO ...

How to request permissions from a bot user in Discord.js version 14?

I need to verify my bot's permissions before it carries out a command. Previously, everything was functioning perfectly with this code: // Discord.js v13 if (interaction.guild.me.permissions.has(Permissions.FLAGS.MANAGE_MESSAGES)) { interaction.re ...

Users are encountering timeout issues when attempting to connect to the Azure Postgres flexible database through the node.js server deployed on the Azure App Service

My node.js express server is deployed on Azure App Services, connecting to an Azure flexible Postgresql database. Strangely, everything works fine when running the server locally, but once it's deployed to Azure App Service, all requests time out: Th ...

Using an iframe to access HTTP content from an HTTPS website

Currently, I am facing an issue with a page that contains an iframe loading an HTML template from an Amazon AWS S3 bucket. Within the iframe, my goal is to take the link of the parent window and add additional parameters. For example, let's say my pa ...

Having trouble creating a polygon from JSON in ESRI ArcGIS Javascript framework?

Can anyone assist with understanding the issue of trying to draw a polygon using the ESRI ArcGIS Javascript API? The image, JSON string, and code snippets provided below outline the code, console output, and expected behavior. Any help would be greatly app ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

Inquiries regarding the distinctive key and component framework of Ant Design

Currently, I am in the midst of a project utilizing react, next.js, and antd. However, an error message has popped up stating: Warning: Each child in a list should have a unique "key" prop. This issue precisely stems from the absence of a uniqu ...

Exploring the Power of Jasmine Testing with Ternary Conditions

Imagine a scenario where we are working with the following snippet of JavaScript code. object = _.isUndefined(object) ? '' : aDifferentObject.property; Is it possible to write a Jasmine test that covers both scenarios? Do we need to use two se ...

Setting up an object with a set expiration using NodeJS and Mongoose

Is there a way to create a temporary entity (like an ad) that will automatically expire after one month using NodeJS with MongoDB? An ideal comparison would be Instagram or Facebook Stories that only last for 24 hours. ...

The GET API is functioning properly on Google Chrome but is experiencing issues on Internet Explorer 11

Upon launching my application, I encountered an issue with the v1/validsColumns endpoint call. It seems to be functioning properly in Chrome, but I am getting a 400 error in IE11. In IE v1/validCopyColumns?category=RFQ&columns=["ACTION_STATUS","ACTIO ...

Updating content with Ajax in Laravel

Hey, I'm currently facing an issue with my update functionality. Below is the blade code snippet: <div class="form-group floating-label" id="role_colaboration1"> <select name="{{$role}}[]" id="role" class="form-control"> ...

Ways to retrieve sorted and updated items in ngx-datatable post-sorting

I am currently utilizing the swimlane/ngx-datatable library to display a list. Within each row of the list, I have implemented an action menu that pops up upon clicking an icon, with dynamically generated items. Challenge: Following sorting, the items app ...

What is causing the Access-Control-Allow-Origin error when using axios?

I have a simple axios code snippet: axios.get(GEO_IP) .then(res => res) .catch(err => err); In addition, I have configured some default settings for axios: axios.defaults.headers["content-type"] = "application/json"; axios.defaults.headers.common. ...

Navigating through different components using React router version 4 and accessing inner

Transitioning from my background in Angular, I am attempting to recreate familiar functionalities using Angular's ui-router. My goal is to establish a main template for the application that features a static sidebar and dynamically changing views bas ...