Angular’s dependency injection provides a mechanism to define in the NgModule’s providers, the parameters with which to construct a component.
I would like to understand the benefits of this mechanism compared to just using a new MyObject in the constructor of the component. I have read a chapter about this subject in the book “ng-book, the complete book on Angular”. One can use DI with 3 types of dependencies: a value, a singleton instance of a class, a factory instantiating new classes.
- for the case of a singleton, one can use the fact that in ES 6 every “CommonJS module” is run only once when using import. I am mentioning an alternative to DI.
shared_dependency.ts:
const myUniqueInstance = new MyCLass()
export default myUniqueInstance
my_component.ts:
import myUniqueInstance from './shared_dependency'
However, there are small differences. For example, an import at the top of the file will be called when the Javascript file is loaded by the browser. With the Angular DI, the actual instantiation of myClass will be delayed until the first time it is needed. If it is never needed, it will not be done. It can be both good and bad. It speeds up the startup time and reduce memory use.
There is an structure difference. The COmmonJS singleton pattern looks like a global variable. The ANgular DI, will pass a variable as an input top the constructor. It is better programming style.
However, I almost never use the CommonJS singleton pattern. THe same can be achieved using new in the constructor. SO I still don’t see the benefits of Angular DI.
- For the case of a factory, we can use:
constructor() {
this.myUniqueInstance = new MyClass()
}
Or you can run new yourself somewhere else and pass it to the constructor.
For testing, one can mock override functions without DI by using babel transpiling. But it is a little tricky and Angular’s DI may be a nicer way to provide mocks in the tests.
Maybe there is a structural benefit to put separated things outside of the component .
Maybe the memory is allocated differently when it is inside a a constructor and not like with the Angular DI.
So my question: what benefits are there with Angular’s dependency injection compared to using new in the constructor? So far, I could not find one. The new in the constructor works fine. ONe can also run new …() and pass the result to the constructor of the component.