Using $ injector vs injection services directly

I was wondering when you will use $injector.get('someService') vs to use this service directly.

Basically, what is the difference between these two codes below?

 angular .module('myApp') .controller('MyController', MyController); /** Difference of this **/ MyController.$inject = ['$rootScope', '$route']; // and more services MyController($rootScope, $route) { /* ... */ } /** And this **/ MyController.$inject = ['$injector']; MyController($injector) { var $rootScope = $injector.get('$rootScope'); var $route = $injector.get('$route'); /* and so on */ } 

If you are not sure what your controller needs, or that you will update it in the future, and you have its refactoring, then using $injector it is much easier to add / remove dependencies.

+5
source share
1 answer

The first approach uses dependency injection, and the second uses a service locator pattern. Dependency injection has the following advantages:

  • It makes components explicitly dependent. For example, you can look at the controller constructor function and immediately find out what dependencies it needs. Using a service locator, you usually don’t know, because the controller can refer to the service locator every time.

  • This makes unit test easier. For example, you can use the $controller service to instantiate a controller and feed it with mock objects using the locals argument. This is certainly easier than defining a bunch of AngularJS services or factories so that $injector can resolve them. When combined, C # 1 gets worse: you may not be aware of all the dependencies a component requires to provide all the necessary layouts.

The service locator offers some flexibility. For example, your code can only use the service if it exists, for example:

 if ($injector.has('serviceA')) $injector.get('serviceA').doSomething() else someSomethingElse() 

When dependencies are introduced, if serviceA does not exist at the time your component was created, you will receive an error message.

As for the convenience of refactoring, I don’t think it’s difficult to add / remove parameters to the constructor function. As pointed out in the commentary on your question, tools like ngAnnotate will help make the announcement DRYer.

Therefore, I would just stick with dependency injection and use only the service locator when it is absolutely necessary.

+6
source

Source: https://habr.com/ru/post/1207544/


All Articles