Dave Dave - 1 month ago 13
AngularJS Question

Why can't I inject a service into Angular factory/injector?

I have written an authentication service (AuthenticationService) I use for calling out to a WEB API. I recently have learned about interceptors. I want to create an interceptor to intercept requests and modify headers based on the state of the AuthenticationService.

I am having some sort of problem with injecting the AuthenticationService into my interceptor. When I do this, my page is broken. I see things like {{MyVariableName}} instead of the value. Also submitting a form does not work. Nothing happens on a button click.

I have no idea what the problem is, because I cannot find any error message or anything to indicate what the problem is. Nothing is in the console. The page is just broken. If I remove the AuthenticationService from the interceptor, everything works again. Below is 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');
}]);


"app" is defined in another JavaScript file (app.js). This also where AuthenticationService is. The service is declared like this:

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 tried using $injector in my interceptor code, but it was worthless. I got an error stating that $injector was undefined at run time.

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


Can anyone tell what my interceptor's problem is with AuthenticationService?

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']);


There is no error present in the console.

Answer

It looks like you have a circular dependency in your interceptor. You're attempting to inject a service that is using $http while at the same time attempting to configure the $httpProvider.

One solution would be to manually inject the authService inside the request property of the interceptor.

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

  var authInjector = {
    request: function (config) {
      var AuthService = $injector.get('AuthService');
      // Do whatever you need to do with AuthService
      config.headers['x-session-token'] = 'test'; 
      return config;
    }
  };
  return authInjector;
}]);