Search code examples
angularangular2-injection

Is there any reason(except unit-tests) to use Angular2 Dependancy Injection?


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?


Solution

  • 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(...);
      }
    }