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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I will try the suggested method
In that link, will the variable 'enabledModules' be available in app.config since I need the values in app.config?
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'])
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.