As documentation says
Dependency Injection is a powerful pattern for managing code dependencies
But does Angular's DI has any sense?
Let's say we have an HeroComponent living in the HeroModule, and it uses HeroService. To use it in HeroComponent we have to:
- Import HeroService in HeroModule
- Inject HeroService in module providers
- Import HeroService in HeroComponent
- Add type or add injected service to component's parameters.
Why don't just
- import HeroService into HeroComponent?
We can export its instance so we can still have a singleton across our app and we can configure our webpack/karma to be still able to import mocks instead of real implementations inside our tests.
Someone can say Angular's DI makes architecture less tightly coupled, but is it true? In Angular 1.x indeed you just specified params in the constructor. But in Angular2 you have to import your dependency additionally, and you have to specify from where. So where is this loosely coupling?
Example:
import { Http } from 'angular2/http';
export class Login {
constructor(http: Http) {
http.whatever()
}
}
To be able to execute our injection, we have to import it. And when we import, we define exactly what service we are going to use. I don't see any difference from above and below example:
import { http } from 'angular2/http'; (instance)
export class Login {
constructor() {
http.whatever()
}}
providers: [{provide: Http, useClass: MyFancyHttp}]
to@NgModule()
then you get something different than what you imported. – Günter Zöchbauerconstructor(http: Http)
and you have to get this Http from somewhere. So you have to import it. From where? – Oskar Kamiński