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

Resolved the time zone problem that was affecting the retrieval of data from the AWS Redshift database in Next

Currently utilizing Next.js for fetching data from AWS Redshift. When running a query from DataGrip, the results display as follows: orderMonth | repeatC | newC 2024-02-01 | 81 | 122 2024-01-01 | 3189 | 4097 However, upon retrieving the same query ...

What methods can I use to prevent a JavaScript array from getting filled during page loading?

Looking for assistance to populate an array using JQuery with option values from multiple select elements. I need the array to reset and fill with new options each time a select element is used. Strangely, despite my efforts, the array appears pre-filled w ...

The notification bar only makes an appearance when necessary

I am currently working on a dynamic piece of code that sends a request to PHP and receives a response. The goal is for the notification bar to fadeIn() and fadeOut() every time there is a new notification. However, I have encountered an issue where the n ...

Requirements detailed in package.json

Suppose we have a client-side application (such as an Ember app). We define the package.json file for our application with its dependencies listed. { name: "my-app", dependencies: { "dep1" : "1.0.0" }, devDependencies: { ...

The hamburger icon seems to be frozen and unresponsive

I'm struggling to get my hamburger icon to reveal the navigation bar when clicked. The icon itself functions properly and adapts to different screen sizes, but the overlay remains stationary. Check out my code on JSFiddle! <html> <head> ...

Having trouble executing an npm script - getting an error message that reads "Error: spawn node_modules/webpack/bin/webpack.js EACCES"

After installing and configuring Linux Mint, I encountered an error when trying to run my project with the npm run dev command. The error message "spawn node_modules / webpack / bin / webpack.js EACCES" keeps appearing. I have attempted various methods fo ...

How can an AngularJs developer effectively transition to learning ReactJS from Facebook?

As an experienced AngularJS developer, I am now looking to delve into the world of ReactJS from the ground up. I'm seeking guidance on what my learning curve should look like as I dive into ReactJS. Any help would be greatly appreciated! I'm ...

When deploying my NodeJs with ExpressJs API to the server, I encounter a 404 error

I am facing a frustrating issue. I have developed an application using NodeJs, ExpressJs, and Angular. The app consists of a client folder driven by Angular and a Server folder housing my ExpressJs REST Api. On my local system, the application runs smooth ...

Async/await function chaining within JavaScript for asynchronous operations

const function1 = () => { let isSuccess = false function2( // The function function2 is synchronous and always returns true or false. If the result is true, I want to change the value of isSuccess to true ) return isSuccess } The func ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

Struggling to align the push menu properly within the Bootstrap framework

I am currently utilizing Bootstrap as my UI framework and attempting to create a push menu on the left side of the page. While I have made progress towards achieving this goal, there are some bugs in the system that I am encountering. Specifically, I am ha ...

Tips for resolving the error "Cannot access the title property of undefined" when utilizing NextJS prerendering

I am preparing this page in advance for a specific post within my Next.js application: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from &apos ...

Why do we recreate API responses using JEST?

I've been diving into JavaScript testing and have come across some confusion when it comes to mocking API calls. Most tutorials I've seen demonstrate mocking API calls for unit or integration testing, like this one: https://jestjs.io/docs/en/tuto ...

Properly executing a for loop

I have devised a method to transform Swagger 1 documentation into Swagger 2. This involves utilizing an array of resources as input for the conversion process. However, I have encountered an issue where the code seems to be skipping ahead and jumping to ...

Is it possible to interact with Java SE jars using JavaScript?

I need to integrate an API that is written in Java with a Client written in JavaScript. Is there any way to use this API, possibly along with other Java-SE JARs, in Webstorm? Any assistance would be greatly appreciated. Thank you! ...

Challenges with cross domain iframes

I am trying to find a way to send a message from an iframe to the parent page at regular intervals, for example: Iframe Domain = www.abc.com Parent Domain = www.xyz.com I have looked into the following resources: Cross domain iframe issue If anyone ha ...

AngularJS $location is not altering the path accurately

There seems to be an issue with the $location.path not directing to the detail.html. When clicking on table rows, all information disappears and only an alert is displayed. Here is a snippet of my controller script: var app = angular.module('list-m ...

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...