Resolved: Angular JS resolves circular dependencies

I encountered a Circular dependency issue while attempting to make a http.post call in a http interceptor:

Circular dependency found: $http <- Ace <- authInterceptor <- $http <- $templateRequest <- $compile

I understand the problem, but I am unsure how to resolve it. I am still new to Angular and sometimes find it confusing. I would appreciate any help you could provide :) Below is the code snippet:

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

app.service('Ace', ['$http', '$q', '$injector', '$window', function($http, $q, $injector, $window) {

    var user = null;

    var getCurrentUser = function() {
        var url = "http://localhost:8080/api/currentuser";

        var response = $http.post(url, {}).then(function(response) {});
        return response;
    };
    return {
        getCurrentUser: getCurrentUser,
    }
}]);

app.factory('authInterceptor', ['$rootScope', '$q', '$window', '$injector', 'Ace',
    function($rootScope, $q, $window, $injector, Ace) {
        return {
            request: function(config) {
                config.headers = config.headers || {};
                if ($window.localStorage.token) {
                    config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
                }
                return config;
            },
            response: function(response) {
                if (response.status === 401) {
                    // handle the case where the user is not authenticated
                } else {
                    Ace.getCurrentUser().then(function() {
                        console.log("Got current user");
                    });
                }
                return response || $q.when(response);
            }
        };
    }
]);

app.config(function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
});

Answer №1

In an attempt to define the pre-processing functionality of $http, injecting authInterceptor into $httpProvider creates a circular dependency issue as authInterceptor also relies on $http.

To resolve this circular dependency problem, you can utilize the $injector service to connect Ace instead.

app.factory('authInterceptor', ['$rootScope', '$q', '$window', '$injector',
function($rootScope, $q, $window, $injector) {
    return {
        response: function(response) {
            if (response.status === 401) {
                // handle the case where the user is not authenticated
            } else {
                var Ace = $injector.get('Ace');
                Ace.getCurrentUser().then(function() {
                    console.log("Got current user");
                });
            }
            return response || $q.when(response);
        }
    };
  }
]);

Another solution is to register the interceptor in a run() block instead of a config() block. However, it is important to note that before the execution of run(), any calls to $http will not involve authInterceptor.

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

Discover the significance of a data attribute's value for effective comparisons

I have a loop that generates random numbers and positions to create 4 answer choices for users. Now, I am trying to determine the value of the clicked button and compare it to the position of the correct answer. However, whenever I try to do this, it retu ...

Bring in all SCSS styles from a single file and apply them to a React component

I am attempting to incorporate the entire SCSS file into a React component. I attempted to use the styleName props but was unsuccessful import React from 'react' import Calendar from 'calendar' import { calendarStyles } from './ ...

Obtain the HTTP cookie from the browser

I am using AngularJS and I need to find a way to prevent the default cookie sent from the server, which has an expiration set to session. Alternatively, I would like to extract the authentication value from this cookie and save it to my own custom cookie f ...

Steps to avoid reinitializing the component upon changing routes in an Angular 9 component

In my component, the width of a chart is stored in a variable (because I can't use style for d3). However, every time the route changes, all variables in this class component become undefined. I have tried using ngIf, services (which also become unde ...

Using Javascript to open a new page and execute a script

I need to be able to launch a new window window.open(url,'_blank'); After that, I want to execute a JavaScript script like this: window.open(url,'_blank').ready("javascript code here"); However, I'm unsure how to accomplish thi ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...

Comparison of Static Site Generation (SSG) with Server-Side Rendering and Client-Side Rendering

The lack of concrete information surrounding the inner workings of Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG) is truly perplexing to me. Despite numerous articles that vaguely touch on these concepts, I have ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...

The message from the XHR Object appears to be undefined, yet it correctly displays the status

I am currently working on an ajax call that is expected to return a 400 http error code. The backend language being used is PHP. Here is my PHP code: header('Content-Type: text/html',true,400); echo $this->upload->display_errors('< ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

Retrieve both the key and corresponding value from a JSON object

I am attempting to extract the key and value pairs from a JSON dataset. $.get(url, function (data) { console.log(data); if (data.Body != null) { console.log(data.Body); } }); These are my current logs: { $id: "1", Exceptions ...

What steps should I follow to update this React Navigation v5 code to v6?

As I delve into my studies on React Native, I came across the deprecation of the tabBarOptions feature. I understand that now we need to include it in screenOptions, but I'm facing issues with implementing this in my code. I tried enclosing them in br ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

Exploring the Power of Nuxt's asyncData Feature for Handling Multiple Requests

Within my application, there is a seller page showcasing products listed by the specific seller. Utilizing asyncData to retrieve all necessary data for this page has been beneficial in terms of SEO. asyncData ({params, app, error }) { return app.$axi ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...

Store the result of the previous AJAX call in a jQuery variable and combine it with the data from the next AJAX response

I am working on a program where I retrieve price values using ajax. My goal is to add the previous price value to the current price value when it is retrieved again. The issue I am facing is that each time I get a new price value, it overrides the previou ...

Issue encountered in Angular 4 due to XSS script in URL causing "Cannot match any routes" error

I've been working on a project in Angular 4 and encountered an issue while setting up routes for a feature module. The error message I'm receiving is Error: Cannot match any routes. Below is the code snippet of the routes I've defined: con ...

Steps for creating a JavaScript session expiry notification:

Ensuring user session continuity is essential, especially before it expires. In a recent quest on Stack Overflow, I inquired about detecting a dead session and alerting the user. A solution involving AJAX/JSON was proposed, but it inadvertently kept the s ...

Issue with Apollo Client - Mutation failing due to undefined property 'data'

When attempting to call a mutation on the client side in Next.js, I encounter an error every time I use the useMutation hook or the client itself, resulting in the following error: Cannot read property 'data' of undefined. See the code snippets b ...