A_J
A_J

Reputation: 1013

Difference between dependency injection by passing argument and by using angular.injector

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.

Upvotes: 1

Views: 209

Answers (1)

Estus Flask
Estus Flask

Reputation: 223259

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.

Upvotes: 1

Related Questions