What is preventing me from injecting a service into an Angular factory/injector?

I came up with an authentication service (AuthenticationService) that I utilize for making calls to a WEB API. Recently, I stumbled upon interceptors and got intrigued. I thought it would be interesting to create an interceptor that can intercept requests and modify headers based on the state of the AuthenticationService.

However, I encountered an issue when trying to inject the AuthenticationService into my interceptor. The moment I did this, things started breaking on my page. Instead of displaying the actual values, I saw something like {{MyVariableName}}. Furthermore, form submission stopped working altogether - nothing would happen when I clicked a button.

Despite my efforts, I could not pinpoint the exact problem. No error messages or hints were displayed in the console. It felt as if the page was simply broken. Removing the AuthenticationService from the interceptor made everything function properly again. Here is the snippet of my interceptor code:

app.factory('authInjector', ['AuthenticationService', function (AuthenticationService) {
var authInjector = {
    request: function (config) {
        config.headers['x-session-token'] = 'test'; 
        return config;
    }
};
    return authInjector;
 }]);

app.config(['$httpProvider', function ($httpProvider) {
       $httpProvider.interceptors.push('authInjector');
}]);

The "app" is defined in a separate JavaScript file (app.js) where AuthenticationService resides. Here's how the service is declared:

app.service('AuthenticationService', function ($http) { ... } 

My scripts are loaded in the following order:

    <script src="~/Scripts/app.js"></script>
    <script src="~/Scripts/injector.js"></script>

I also attempted to use $injector in my interceptor code, but it proved to be unhelpful. I received an error indicating that $injector was undefined at runtime.

var AuthService = $injector.get('AuthenticationService');

If anyone has insights into what might be the issue with my interceptor and the AuthenticationService, I would greatly appreciate it.

Thanks

Edit: Requested information:

<html ng-app="MyAppName">

app.js:

angular.module('MyAppName').controller('LoginController', function ($scope, $rootScope, $window, AuthenticationService) {

var app = angular.module('MyAppName', ['ngRoute', 'ngSanitize', 'ngMaterial', 'ngMessages', 'material.svgAssetsCache']);

No errors are shown in the console.

Answer №1

It appears that there is a dependency loop in your interceptor. You are trying to inject a service that relies on $http while also configuring the $httpProvider at the same time.

One possible solution is to manually inject the authService within the request function of the interceptor.

app.factory('authInjector', ['$injector', function($injector) {

  var authInjector = {
    request: function (config) {
      var AuthService = $injector.get('AuthService');
      // Perform any necessary actions with AuthService
      config.headers['x-session-token'] = 'test'; 
      return config;
    }
  };
  return authInjector;
}]);

Answer №2

Implement this inside your authInjector:

var AuthService = $injector.get('AuthService');

replace it with:

app.factory('authInjector', ['AuthService', function (AuthService) {

to:

app.factory('authInjector', ['$injector', function ($injector) {

sequence of scripts:

<script src="~/app/app.js"></script> // initialize the app and its dependencies
<script src="~/app/authentication.service.js"></script> // set up the authentication service
<script src="~/app/auth-injector.service.js"></script> // create the interceptor factory
<script src="~/app/app.config.js"></script> // add the interceptor to httpProvider

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

Node.js's async functions seem to be running sluggishly

My list of queries is all set and ready to go: var array = [ 'UPDATE EVALUATION SET mark = "16" WHERE id_eval = "21" AND id_usr = "125"', 'UPDATE EVALUATION SET mark = "9" WHERE id_eval = "22" AND id_usr = "125"', ...

tips for repurposing a jquery function

Similar Question: JQuery: Issue with $(window).resize() not triggering on page load In my jQuery code snippet below, I am trying to make a function work both on window resize and page load without duplicating the code. The current implementation works ...

Adjusting ng-required in AngularJS for both empty values and -1

When an empty value or -1 is selected in my form, it should display an error message saying "This field is required". I have explored two possible solutions: 1. Using ng-required with regular expression. 2. Writing ctrl.$validators.required in the dir ...

How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){ var parentElement = document.getElementById("menuItem1"); var lis = parentElement.getElementsByTagName("ul"); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute("style","display: block"); } } When the button is clicke ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...

"Is there a way to extract a value from a JSON object using

I have an object with the following key-value pairs: { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812', 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1&a ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...

The output from the Angular .then function is not showing up on the webpage

Within my stucontrollers.j, I have the following code: /// <reference path="../angular.js" /> var stucontrollers = angular.module("stucontrollers", []); stucontrollers.controller("GetStudentsList", function GetStudentsList($scope, $http) { $ ...

Is there a way to arrange elements in an array based on the second value in each nested array?

I need help organizing an object {a: 1, b: 20, c: 3, d: 4, e: 1, f: 4} into the following format {a: 1, e: 1, c: 3, d: 4, f: 4, b:20} (sorting the object numerically in ascending order) using a specific set of steps. Here are the steps I have outlined: ...

Creating a user-friendly form in a Nuxt/Vue application that enables dynamic attribute creation

I am currently working on designing a form that enables users to create different variations for a product within a Nuxt/Vue application. The goal is to provide users with the ability to specify attributes for each variation using a text field. These attr ...

The object NativeModules from the 'react-native' requirement is currently empty

At the top of one of the node_modules utilized in my project, there is a line that reads: let RNRandomBytes = require('react-native').NativeModules.RNRandomBytes However, I've noticed that require('react-native').NativeModules ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

Having some trouble implementing the functionality of hiding a data series in HighCharts using `{ data: [], visible: false }` notation

I am currently working on creating a graph that displays multiple series obtained from JSON data in a MySQL database. My goal is to have the graph show only one series initially. Thankfully, HighCharts offers an option to achieve this as demonstrated below ...

Issue with jQuery click event not activating on initial click but functioning properly on the subsequent click

I am currently implementing the jquery.ime editor in my project, which allows for multi-language editing capabilities. The library I am using can be found here. By default, the language JSON files are loaded on "change" events. However, I would like this f ...

Socket.io continuously refreshing and updating multiple instances

Incorporating socket.io into a small React application, I configured all the listeners within the "componentWillMount" method. See the code snippet below for reference: componentWillMount() { const socket = io(); socket.on('update', f ...

Ionic event for managing app closure

I have a process running in the background and I need to ensure it is terminated before the app is closed from the recent apps list (by swiping right with the square button). My app utilizes a plugin for obtaining the current location called https://githu ...

Ways to obtain parameter from URL in Express without diving into the request object

const express = require('express'); const app = express(); app.use('/', anyroute); // in anyroute file router.route('/:id').get(controlFunction) controlFunction(req, res, res)=> { // Here we can get the "id" fr ...

Is there a way to fetch information from a separate collection and integrate it into my mongoose object?

I am currently working on an application using mongoDB and NodeJS for the backend, with Angular as the front end. One of the challenges I'm facing is integrating user data into the bid creation function within my app. Despite my efforts, I can't ...

Is it possible for me to set a timer on the 'keyup' event in order to decrease the frequency of updates?

The code I currently have is functional: $wmdInput.on('keyup', function () { var rawContent = $wmdInput.val(); scope.$apply(function () { ngModel.$setViewValue(rawContent); }); }); Unfortunately, it appears to slow down my t ...