JavaScript Edu Resources. Angular Courses. React Tutorials. Join us!

Dependency Injection in Angular 2

  • Before we jump right into the new stuff, lets first understand what dependency injection is, and what the problems with the DI in Angular 1 are.
  • As we all know, Angular 1 has it’s own DI system which allows us to annotate services and other components and let the injector find out, what dependencies need to be instantiated.
  • For example, the following code shows how we can annotate our class in Angular 1:

    Then, we register our as a service and whenever we ask for it, we get a singleton instance of it without needing to care about creating needed dependencies for the car.

  • The following graphic illustrates required components in the new DI system:

    The DI in Angular basically consists of three things:

    Okay, now that we have an idea of what the concept looks like, lets see how this is translated to code.

  • We can rewrite this code to TypeScript, which feels a bit more natural:

    Nice, our class declares it’s own dependencies and the DI can read that information to instantiate whatever is needed to create an object of .



Dependency Injection in Angular by thoughtram


https://twitter.com/


https://twitter.com/intent/tweet/?text=Dependency%20Injection%20in%20Angular&url=http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html


Comments are closed, but trackbacks and pingbacks are open.