Error in initializing UI-router wrapper due to circular dependency in Angular.js

I've been following the angular style guide of John Papa (https://github.com/johnpapa/angular-styleguide#routing) and implementing a custom wrapper for angular ui-router as suggested. However, I'm encountering an issue with the wrapper causing a circular dependency error when trying to inject $state:

Uncaught Error: [$injector:cdep] Circular dependency found: $rootScope <- $timeout <- $$rAF <- $$animateQueue <- $animate <- toastr <- logger <- $exceptionHandler <- $rootScope <- $state <- routerHelper

I attempted manual injection of $state using $injector but unfortunately received an unknown provider error.

Below is the code snippet in question:

(function() {
'use strict';

angular
    .module('blocks.router')
    .provider('routerHelper', routerHelperProvider);

routerHelperProvider.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider', '$injector'];

function routerHelperProvider($locationProvider, $stateProvider, $urlRouterProvider) {


    this.$get = RouterHelper;

    $locationProvider.html5Mode(true);

    RouterHelper.$inject = ['$state'];

    function RouterHelper($state) {
        var hasOtherwise = false;

        var service = {
            configureStates: configureStates,
            getStates: getStates
        };

        return service;

        function configureStates(states, otherwisePath) {
            states.forEach(function (state) {
                $stateProvider.state(state.state, state.config);
            });
            if (otherwisePath && !hasOtherwise) {
                hasOtherwise = true;
                $urlRouterProvider.otherwise(otherwisePath);
            }
        }

        function getStates() {
            return $state.get();
        }
    }

}
})(); 

Answer №1

The issue seems to stem from toastr rather than the UI router code itself.

John Papa uses examples based on the standard 'toastr' package, not the 'angular-toastr' package.

Toastr Package: https://github.com/CodeSeven/toastr

Angular-Toastr Package: https://github.com/Foxandxss/angular-toastr

When working with the 'toastr' package, Toastr is registered as a constant in the global toastr instance:


    .module('app.core')
    .constant('toastr', toastr);

This makes it possible to inject Toastr into the logger service:

logger.$inject = ['$log', 'toastr'];

/* @ngInject */
function logger($log, toastr) {

However, if you opt for the angular-toastr package, Toastr introduces dependencies on various Angular objects:

$rootScope <- $timeout <- $$rAF <- $$animateQueue <- $animate <- toastr

This results in a circular dependency since $rootScope handles exceptions and relies on the logger/toastr objects:

toastr <- logger <- $exceptionHandler <- $rootScope

A solution to address this circular dependency issue was not immediately clear. As a temporary fix, I modified the logger service to delay resolving the toastr dependency using $injector. While not ideal, this allowed me to address other pressing matters.

logger.$inject = ['$log', '$injector']; // 'toastr'

/* @ngInject */
function logger($log, $injector) { // toastr

    var service = {
        showToasts: true,

        info    : info,
        success : success,
        warning : warning,
        error   : error,

        // bypass toastr and log directly to console
        log     : $log.log
    };

    return service;
    /////////////////////

    function info(message, data, title) {
        var toastr = $injector.get('toastr');

        toastr.info(message, title);
        $log.info('Info: ' + message, data);
    }

    function success(message, data, title) {
        var toastr = $injector.get('toastr');

        toastr.success(message, title);
        $log.info('Success: ' + message, data);
    }

    function warning(message, data, title) {
        var toastr = $injector.get('toastr');

        toastr.warning(message, title);
        $log.warn('Warning: ' + message, data);
    }

    function error(message, data, title) {
        var toastr = $injector.get('toastr');

        toastr.error(message, title);
        $log.error('Error: ' + message, data);
    }

}

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

Issue with a input element having relative positioning within a flexbox

Objective: Aim to align the middle DIV (MIDDLE) within a flexbox row in the center. Issue: The right element includes an input element with relative positioning. Consequently, the middle DIV element (MIDDLE) is no longer centered but instead shifted to th ...

Template for developing projects using JavaScript, HTML5, and CSS3 in Visual Studio 2013

After recently downloading Visual Studio 2013 Express for Web, I am struggling to figure out how to deploy projects that only consist of JavaScript, HTML5, and CSS3. Despite searching online for JavaScript templates and even trying to download Visual Stu ...

Material-UI Masonry: Eliminate excess spacing on the right side

When utilizing Material-UI, I encountered an issue where the width of the Masonry Component does not completely fill the width of its parent container. The empty space left has a width exactly equal to the spacing between elements, which is understandable ...

Attempting to employ the .reduce method on an object

Currently, I am faced with the task of summing a nested value for all objects within an object. The structure of my object is as follows: const json = [ { "other_sum": "1", "summary": { "calculations" ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

The MongoDB regex is failing to provide the expected outcome

I'm facing an issue with searching data in MongoDB. I have a table with approximately 5000 entries of data that need to be searched based on multiple columns with specific priority criteria. The first priorities for the search are symbol, name, co_nam ...

Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide TEST: import { render, screen } from 'test-util'; import { Sideb ...

Control the switch for CSS selectors

Consider the following scenario where CSS rules are defined: <style> table {background:red;} div {background:green;} </style> In addition, there is HTML code that calls a JavaScript function: <table onclick="tu ...

Disabling the Bootstrap tooltip feature is a quick and easy process

Is there a way to turn off bootstrap tooltip on my website? I activated it with the code below: function activateTooltip() { const toolTips = document.querySelectorAll('.tooltip'); toolTips.forEach(t => { new bootstrap.Tooltip(t); } ...

AngularJS - Dynamically change the placeholder value

<md-input-container class="md-block hide-error-space" flex="25"> <input required name="password" ng-model="password"> </md-input-container> Here is a form field where the user can enter their password. <md-input-container md-no-float ...

Have you considered utilizing "call for('express')()" instead?

When creating a simple Web server with NodeJS and Express, most tutorials provide examples like the following: const express = require('express'); const app = express(); app.listen(3000, () => console.log("Started")) app.get(' ...

Tips for identifying the highest number of repeating "values" in a JavaScript array

My problem is similar to the question asked here: Extracting the most duplicate value from an array in JavaScript (with jQuery) I tried the code provided, but it only returns one value, which is 200. var arr = [100,100,200,200,200,300,300,300,400,400,4 ...

The offsetTop property of Angular's nativeElement always returns a value of 0

I am currently working on a menu that will automatically select the current section upon scrolling. However, I am running into an issue where I am consistently getting a value of 0 for the offsetTop of the elements. The parentElement returns a value for of ...

Is it possible to create a query selector that is able to find an element based on its attributes while also excluding elements with a specific class name?

Imagine you have elements that look like this: <div class="a b" data-one="1" data-two="2"></div> <div class="c" data-one="1" data-two="2"></div> <div class="b" data-one="1" data-two="2"></div> Is there a way to selec ...

What is the reason this switch statement functions only with one case?

Why is the switch statement not functioning properly? It seems to correctly identify the values and match them with the appropriate case, but it only works when there is a single case remaining. If there are multiple cases to choose from, nothing happens. ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...

Implementing JavaScript functionality based on a specific body class

Is there a way to execute this script only on a specific page with a particular body class? For example, if the page has <body class="category-type-plp"> How can I target my script to work specifically for "category-type-plp"? plpSpaceRemove: fun ...

The Kendo Date Picker is failing to update properly when the k-ng-model is modified

I am facing an issue with my code involving two date pickers and one dropdown list. I want the date pickers to change based on the selected item from the dropdown list. Here is the relevant portion of my code: $scope.toolbarOptions = { i ...

Tips for resolving the error: finding the right loader for handling specific file types in React hooks

data = [{ img: '01d' }, { img: '02d' }] data && data.map((item) => ( <img src={require(`./icons/${item['img']}.svg`).default} /> )) I am facing an issue with the message Error: Module parse failed: U ...

VueX getter not functioning with Async/Await, while log function does work

I am working on a situation where I have a collection of conversations associated with userIDs that I need to iterate through. Within this loop, I must make a call to Firebase to retrieve the corresponding userNames and then generate an object containing t ...