Issues related to the timing of AngularJS dependency injection

Encountering an issue with AngularJS dependency injection and timing. Below is the code snippet along with the error message:

var module = angular.module('Demo', []);

module.factory('demo', function () {
        return {
            data: {},
        };
    });

module.provider('foo', ['demo', function(demo) {
    console.log(demo);

    this.$get = function() {
    };
}]);

Error Message:

Uncaught Error: [$injector:modulerr] Failed to instantiate module Demo due to:
Error: [$injector:unpr] Unknown provider: demo

Interestingly, adding a setTimeout function at the end resolves the issue. However, this is not the ideal solution as it's considered a hack.

var module = angular.module('Demo', []);

module.factory('demo', function () {
        return {
            data: {},
        };
    });
setTimeout(function(){
module.provider('foo', ['demo', function(demo) {
    console.log(demo);

    this.$get = function() {
    };
}]);

});

For reference, here is the problem demonstrated on JSFiddle: http://jsfiddle.net/zcf7rb4s/1/

Answer №1

Adding demo as a dependency is not possible at that point since it does not exist yet. This is how the $injector operates. However, you can specify demo as a dependency in the $get function of the provider. This will be executed by the $injector after all providers have been defined.

Take a look at this example:

<div ng-app="Demo">
    <div ng-controller="test">{{x}}</div>
</div>

Here are the definitions:

var module = angular.module('Demo', []);

module.factory('demo', function () {
        return {
            data: {x: 'x'},
        };
    });

module.provider('foo', function() {
    this.$get = function(demo) {
        return {
            demo: demo
        };
    };
});

module.controller('test', ['$scope', 'foo', function($scope, foo) {
    $scope.x = foo.demo.data.x;
}]);

The code within the factory and provider is executed during "step 1". Subsequently, AngularJS binds the controller in "step 2". It utilizes $injector to inject the dependencies that were defined earlier in "step 1". Your usage of $timeout may seem to replicate this behavior, but it is not the correct approach.

Answer №2

To incorporate into the provider, use the following method:

module.provider('bar', function() {
    this.$fetch = ['example', function(example) {
        console.log(example);
    }];
});

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

Incorporate an image into the React state in order to showcase it within a personalized

Objective I am aiming to create a dropdown menu that allows users to select images instead of text. Context I have integrated a react dropdown component into my file, and it works well with text options. However, I am facing difficulties in displaying i ...

Find and filter the values in the range.getValues() array that correspond to the first element in apps script

In the spreadsheet provided, I have compiled a list of cities in different states of my country. This information will be utilized in a form; however, it is not feasible for users to sift through an extensive list of all cities listed. Therefore, I am look ...

Use JSON data to populate a dynamic bar chart in Highcharts

As a beginner in parsing JSON objects to highcharts, I am trying to create a basic bar graph. I have managed to set up the title of the graph, but I am having trouble displaying the series that I want to show (count as series and qpAnswer as xAxis). Below ...

How can I prevent an HTML element from losing focus?

Currently, I am developing an online editor that requires accurate character inputs. To achieve this, I have implemented the jQuery.onKeyPress event on a textarea element. This approach was chosen because obtaining character inputs from the body directly p ...

When attempting to delete a resource using an HTTP request in Insomnia, I encountered a TypeError stating that it was unable to read the property 'id'

I recently started using Express and am in the process of setting up the Delete function for my database within the MERN stack. While testing my CRUD operations using Insomnia, I have encountered an issue specifically with the Delete operation. The proble ...

In what way does Google+ make their logo come to life on the left side of the navigation bar when the scrollbar is minimized?

I'm curious about the animation Google+ uses to make their logo slide in on the navigation bar when it shrinks. I've managed to shrink the scrollbar on scroll, but I can't quite replicate their technique for animating the icons. I'm eag ...

Latest versions of Bootstrap are facing issues with the functionality of the Carousel feature

I'm struggling to create a basic carousel, but for some reason, it's not functioning properly. I attempted to use the sample code provided by Bootstrap's documentation, but it doesn't behave as expected (slides won't transition and ...

Reorganize the JSON data to match the specified format

{ "EUR": { "Description": "", "Bid": "1.1222", "Region": "", "Bid1": "1.1283", "CurrencyCode": "EUR", "FeedSource": "1", "Ask": "1.1226", "ProviderName": "TEST 1", "Low": "1.1195", ...

Obtaining information from a database and integrating it into introjs utilizing JSON

Currently, I am using IntroJs and JSON to call the introjs. I am wondering if it is possible to store data/text/info in a database and then retrieve it using JSON? <h2 id="welcomeMsg">Welcome back,<asp:Label ID="lbl_WelcomeName" runat="server" Te ...

Utilize AngularJS to upload Excel files and identify any potential issues with SOA APIs

Currently, I am encountering difficulties in uploading files through API calls. Unfortunately, I lack the necessary knowledge to resolve this issue. Is there anyone who can guide me on how to fix it? Here is my existing AngularJS code: <!DOCTYPE html ...

Is it possible to improve the cleanliness of a dynamic button in Jquery?

I've just finished creating a dynamic button on the screen as per my boss's request. When this button is clicked, it triggers an email window for feedback submission. My aim is to streamline this script so that I can avoid digging into ASP marku ...

Unable to retrieve JSON information using AJAX

Trying to retrieve data from the server without refreshing the page using AJAX. The issue is that the data appears as text rather than in JSON format. Here is my code: $.ajax({ type: "GET", url: "http://localhost:8080/search?key=" + QUERY + "", ...

Having two custom directives within the same module is causing functionality issues

While working with a module called validationMod for form validation, I encountered an issue with two custom directives. Surprisingly, only the second directive was executing, displaying an alert for test2. However, upon removing the second directive, the ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

Navigational inconsistency with SVG icons integrated into Bootstrap Navbar

Bootstrap offers icons in embedded SVG format. These SVG tags can be directly added to HTML code. However, when I included the SVG tag in my navbar, the icon did not appear centered even after using the vertical-align: middle CSS property. The icon did not ...

JavaScript throws an error because document is not defined

view image description hereWhy am I encountering an error after installing node.js and running various JavaScript commands? It seems like the issue is not with my code, but rather that node.js is failing to establish a connection with the server. view ima ...

"Enhance Your Sublime 3 Experience with a Jade Syntax Highlighter, Linting, Auto Complete, and

After trying out the recommended packages for Sublime Text, I'm still not satisfied with how they handle syntax highlighting, code linting, and auto suggestion. Could anyone recommend a comprehensive package specifically for Jade? ...

Turn off the perpetual active mode

I have a situation where a link maintains its active state after being dragged and released. This is causing an issue that I need to address. For example, you can see the problem here: http://jsfiddle.net/Ek43k/3/ <a href="javascript:void(0);" id="foo ...

Nested scrolling bars within each other

Currently, I am importing photos from a Facebook page and displaying them on my jQuery mobile webpage using the photoSwipe plugin. However, there seems to be an issue with the final appearance of the images. Pay attention to the image where the red arrow ...

Ways to remove items from Vuex store by utilizing a dynamic path as payload for a mutation

I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element. Triggering the action deleteOption(path, key) { this.$store.d ...