Angular 2 - Dependency injection
Why Dependency injection?
At
the heart of Angular, and one of its most powerful features as a
framework, is how it brings dependency injection to JavaSript. Dependency injection, or DI for short, is the concept of inversion of control, or IOC
for short, where you architect code in a way that you provide
modules with other modules it needs to get some work done instead of
having your modules go out and get other modules on their own.
DI allows you to write decoupled code that is
easier to unit test and to work with. In the Angular world, this
allows you to write these modular components and even services within your
applications and simply tell Angular what you want to use and where
want to use them.
Angular will handle constructing instances of
those and sending them to your code where needed.
DI Usage:
The most common place you use DI is in
your class constructors. So constructors for components, directives,
pipes, and services you write can leverage the way Angular does DI.
We can simply declare types on your constructor
parameters with some help from Typescript, and Angular will interpret
that and make sure you receive an instance of that type when your
constructors run.
We can also leverage DI through things
like component metadata properties for directives and providers.
We can even do some DI at the bootstrap phase of
an Angular app, setting up your dependency graph when your app starts up and
getting that delivered through all aspects of your app.