I'm trying to figure out why we need Angular2 Dependancy Injection. Case with tests is clear: we could easily mock any Service. But could you provide any other reason?
Asked
Active
Viewed 38 times
1 Answers
1
Using DI leads to a better architecture where classes are more loosely coupled. This is also the reason such code is better testable.
DI not only allows to easily mock services, it also allows easy configuration for production scenarios.
You can provide different configuration values or service implementations by just changing one file but affecting the whole application.
Therefore the main advantage that makes it easier for testing also has advantages outside of testing.
abstract class ConfigBase {
get someConfigValue():number;
}
@Injectable()
class MyConfig1 extends ConfigBase {
get someConfigValue():number {
return 1;
}
}
@Injectable()
class MyConfig2 extends ConfigBase {
get someConfigValue():number {
return 2;
}
}
let config = new MyConfig1();
let serverUrl = 'http://example.com';
@NgModule({
providers: [
{provide: 'serverUrl', useValue: 'http://},
{provide: ConfigBase, useValue: config}
],
...
})
@Injectable()
class MyService {
constructor(
private http:Http,
@Inject('serverUrl') private serverUrl:string,
private config:ConfigBase
) {}
doSomething() {
console.log(this.config.someConfigValue);
this.http.get(this.serverUrl).subscribe(...);
}
}

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
could I ask you to provide an example of different configuration via DI? – Stepan Suvorov Oct 30 '16 at 18:39
-
I updated my answer. You can change the configuration by modifying the lines that start with `let`. (these classes can be in different files) – Günter Zöchbauer Oct 30 '16 at 18:47