1

I had a use-case where I wanted to make the session timeout of the application configurable by making a call to REST api and get the value using $http. But as I found in this link how to inject dependency into module.config(configFn) in angular that services cannot be injected in config method, I have found this solution to make this work in the config:

var $http = angular.injector(['ng']).get('$http');

This is working fine, what is the difference between the two approaches and why this is working ? Also is there any limitation of using this approach.

A_J
  • 977
  • 4
  • 16
  • 44

1 Answers1

1

angular.injector creates a new injector (application instance). It is misused most times and rarely ever needed in production.

It will have its own $http, $rootScope, $q, etc instances:

angular.injector(['ng']).get('$http') !== angular.injector(['ng']).get('$http');

The use of angular.injector in config block is an antipattern. It will result in untestable and potentially buggy code. $http request is asynchronous, application initialization will be completed first and likely result in race condition.

Most times when a need for $http in config appears, it should be performed in route resolver. If the response contains information that should be used to configure service providers and should be available in config block, it should be fetched prior to application bootstrap - in fact, there should be two applications, as shown here.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Thanks I will try the suggested method – A_J Sep 16 '17 at 10:48
  • In that link, will the variable 'enabledModules' be available in app.config since I need the values in app.config? – A_J Sep 20 '17 at 07:26
  • It won't. In that example data that was received (enabledModules) is a list of modules that should be bootstrapped. In your case it will be instead: `angular.module('app').constant('data', data); angular.bootstrap($document.find('body'), ['app'])` – Estus Flask Sep 20 '17 at 07:47
  • But how will I get that data from REST service. I don't want to hard code it but get it from REST api call – A_J Sep 20 '17 at 09:19