Resetting the Angular provider configuration whenever the service is injected into a different location

Trying to wrap my head around a rather complex issue here. I have a service set up as a provider in order to configure it. Initially, this service has an empty array of APIs which can be dynamically added to by various configuration blocks. When adding APIs, I can see the array growing with console.log messages.

However, when I inject this service into something else, like an $http interceptor function, and try to retrieve the array using a service method, I keep getting an empty array.

I believed that since all config blocks run first, by the time the $http call interception happens, the array should already be populated with APIs. But that doesn't seem to be the case.

Below is some sample code:

angular.module('authModule').provider('authService', function(){

    var _apis = [];

    return({
        addApi: addApi,
        $get: instantiateAuth
    });

    function addApi(newApi){
        _apis.push(newApi);
        console.log("API added", _apis);
    }

    function instantiateAuth() {
        return({
            getApis: function(){
                console.log("Getting APIs", _apis);
                return _apis;
            }
        });
    }

})


.config(function($httpProvider){

    $httpProvider.interceptors.push(function($log, $rootScope, $q) {
        return {
            request: function(config) {
                var injector = angular.injector(['ng', 'authModule']);
                var authService = injector.get('authService');
                console.log("apis", authService.getApis());
            }
        };
    });

});

And here's an example of a config block:

angular.module('myModule').config(function ($provide, authServiceProvider) {

    authServiceProvider.addApi({
        url: 'https://apiurl.com',
        other: 'stuff'
    });

    authServiceProvider.addApi({
        url: 'https://apiurl2.com',
        other: 'stuff'
    });

});

Despite seeing the array grow with each call to the addApi method in the config block, the array appears empty when accessed through authService.getApis() during the HTTP call interception.

Any insights or assistance on this puzzling issue would be greatly appreciated.

UPDATE:

The crux of the problem seems to lie in this line of code:

var injector = angular.injector(['ng', 'authModule']);

It appears that my provider is being reset or recreated each time this line executes. Perhaps my understanding of how the injector works is flawed. Initially, I tried injecting my authService directly as a parameter in the function, but faced a circular dependency due to the need for authentication service to open a modal window which relies on http service, while my http calls are intercepted by the authentication service for user authentication checks.

Answer №1

Indeed, the function

angular.injector(['ng', 'authModule'])
creates a fresh injector instance, akin to starting a new application:

angular.injector(['authModule']) !== `angular.injector(['authModule'])

The ng module is automatically loaded and does not need to be explicitly stated. Singleton services are unique only within the same injector instance:

injector.get('authService') === injector.get('authService');

However,

angular.injector(['authModule']).get('authService') !== `angular.injector(['authModule']).get('authService')

To maintain the current injector instance (which is typically preferred), utilize the $injector service:

$httpProvider.interceptors.push(function($log, $rootScope, $q, $injector) {
    return {
        request: function(config) {
            var authService = $injector.get('authService');
        }
    };
});

In dealing with circular dependencies, utilizing $injector.get proves to be a reliable and direct approach.

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

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

Converting JSON data into a table using jQuery, with certain columns hidden from view

I am currently working on developing a mobile app using jQuery Mobile and JSON. I have encountered two separate questions: 1) I have a JSON data set which includes fields such as id, name, surname, point, and mail. In my table that lists this data, I init ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Extract a specific pattern from a string using Javascript

Currently, I am attempting to extract a specific string from a tag in javascript using the following code: document.querySelector('.title h2').textContent However, when I execute this code, I am getting a result that includes unnecessary double ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

Is the Await keyword failing to properly pause execution until the promise has been fulfilled?

I'm currently working on manipulating a variable within an async function, and I've noticed that the variable is being returned before the completion of the data.map function below. Even though I have the await keyword in place to pause the code ...

Vite and Transloadit encountered a type error: Unable to access properties of undefined when trying to read 'Resolver'

Currently, I am developing a Vite application using Vue 3.x that involves interactions with images/PDFs through Transloadit. While working on creating my own plugin for Transloadit integration, I encountered some issues. Initially, I managed to resolve an ...

Vue Testing Utilities - issue with data not updating upon click event activation

I recently created a basic test using Vue Test Utils: import { mount } from '@vue/test-utils' const App = { template: ` <p>Count: {{ count }}</p> <button @click="handleClick">Increment</button> `, ...

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

InvalidType Error: The roles provided are not in the correct format, it should be a Role, Snowflake, or an Array/Collection of Roles or Snowfl

Having trouble setting up multiple select menu options on Discord.js v14. I'd like to assign more than one role to a member when multiple options are chosen in the dropdown menu. However, I'm encountering this error message: TypeError [Invalid ...

Updating the AngularJS promise does not reflect changes in the scope set to a single item within an array

I am working with two controllers: function AppCtrl($scope, $dataService) { $scope.projects = $dataService.data.projects; } function ProjectCtrl($scope, $route, $q) { //Accessing the current project from the projects array $scope.project = $s ...

Scraping multiple websites using NodeJS

I have been immersing myself in learning NodeJS and experimenting with web scraping a fan wikia to extract character names and save them in a json file. I currently have an array of character names that I want to iterate through, visiting each URL in the a ...

Executing a script that has been inserted into the page post-loading

I'm facing an issue where the script tag at the bottom of my project is not being executed after adding new pages later on. Main const fetch = (url, call) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

Combining Summernote images with Node.js using Express.js

While there are numerous solutions available for handling the Summernote file-upload in PHP, I have struggled to find a satisfactory solution for Node.js. Here is My JavaScript: $(document).ready(function() { // $('#summernote').summernote( ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

Receiving a commitment from an Angular Resource

When working with $resource in Angular for CRUD operations, I'm encountering some confusion regarding the usage of different resource methods. From what I've observed, the "regular" methods like save() and get() appear to execute synchronously. ...