2016-02-06 02:27:06 -05:00
include ../_util-fns
2016-04-23 15:44:09 -04:00
2015-11-10 13:31:46 -05:00
:marked
2015-12-11 16:18:37 -05:00
We learned the basics of Angular Dependency injection in the
[Dependency Injection](./dependency-injection.html) chapter.
2015-11-10 13:31:46 -05:00
2016-02-29 14:37:14 -05:00
Angular has a Hierarchical Dependency Injection system.
2015-12-11 16:18:37 -05:00
There is actually a tree of injectors
that parallel an application's component tree.
2015-10-17 19:40:10 -04:00
We can re-configure the injectors at any level of that component tree with
interesting and useful results.
2016-01-14 05:47:38 -05:00
2015-12-11 16:18:37 -05:00
In this chapter we explore these points and write some code.
2016-01-14 05:47:38 -05:00
2015-12-11 16:18:37 -05:00
[Live Example](/resources/live-examples/hierarchical-dependency-injection/ts/plnkr.html).
2015-10-17 19:40:10 -04:00
2015-11-10 13:31:46 -05:00
.l-main-section
:marked
2015-10-17 19:40:10 -04:00
## The Injector Tree
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
In the [Dependency Injection](./dependency-injection.html) chapter
we learned how to configure a dependency injector and how to retrieve dependencies where we need them.
2015-11-10 13:31:46 -05:00
2016-01-14 05:47:38 -05:00
We oversimplified. In fact, there is no such thing as ***the*** injector!
2015-12-11 16:18:37 -05:00
An application may have multiple injectors!
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
An Angular application is a tree of components. Each component instance has its own injector!
The tree of components parallels the tree of injectors.
2016-01-14 05:47:38 -05:00
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
.l-sub-section
2015-11-10 13:31:46 -05:00
:marked
2016-01-14 05:47:38 -05:00
Angular doesn't *literally* create a separate injector for each component.
Every component doesn't need its own injector and it would be horribly inefficient to create
2015-12-11 16:18:37 -05:00
masses of injectors for no good purpose.
2016-01-14 05:47:38 -05:00
2015-12-11 16:18:37 -05:00
But it is true that every component ***has an injector*** (even if it shares that injector with another component)
and there may be many different injector instances operating at different levels of the component tree.
It is useful to pretend that every component has its own injector.
2015-11-10 13:31:46 -05:00
:marked
Consider a simple variation on the Tour of Heroes application consisting of three different components:
`HeroesApp`, `HeroesListComponent` and `HeroesCardComponent`.
The `HeroesApp` holds a single instance of `HeroesListComponent`.
2015-10-17 19:40:10 -04:00
The new twist is that the `HeroesListComponent` may hold and manage multiple instances of the `HeroesCardComponent`.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
The following diagram represents the state of the component tree when there are three instances of `HeroesCardComponent`
open simultaneously.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
figure.image-display
2015-12-11 16:18:37 -05:00
img(src="/resources/images/devguide/dependency-injection/component-hierarchy.png" alt="injector tree" width="500")
2015-11-10 13:31:46 -05:00
:marked
2015-10-17 19:40:10 -04:00
Each component instance gets its own injector and an injector at one level is a child injector of the injector above it in the tree.
2015-11-10 13:31:46 -05:00
When a component at the bottom requests a dependency, Angular tries to satisfy that dependency with a provider registered in that component's own injector.
If the component's injector lacks the provider, it passes the request up to its parent component's injector.
If that injector can't satisfy the request, it passes it along to *its* parent component's injector.
2015-10-17 19:40:10 -04:00
The requests keep bubbling up until we find an injector that can handle the request or run out of component ancestors.
If we run out of ancestors, Angular throws an error.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
.l-sub-section
2015-11-10 13:31:46 -05:00
:marked
There's a third possibililty. An intermediate component can declare that it is the "host" component.
2015-10-17 19:40:10 -04:00
The hunt for providers will climb no higher than the injector for this host component.
We'll reserve discussion of this option for another day.
2015-11-10 13:31:46 -05:00
:marked
2015-10-17 19:40:10 -04:00
Such a proliferation of injectors makes little sense until we consider the possiblity that injectors at different levels can be
configured with different providers. We don't *have* to re-configure providers at every level. But we *can*.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
If we don't re-configure, the tree of injectors appears to be flat. All requests bubble up to the root injector that we
configured with the `bootstrap` method.
2015-11-10 13:31:46 -05:00
2015-11-11 06:16:20 -05:00
The ability to configure one or more providers at different levels opens up interesting and useful possibilities.
2015-11-10 13:31:46 -05:00
Let’ s return to our Car example.
2016-02-29 14:37:14 -05:00
Suppose we configured the root injector (marked as A) with providers for `Car`, `Engine` and `Tires`.
2015-10-17 19:40:10 -04:00
We create a child component (B) that defines its own providers for `Car` and `Engine`
2015-11-10 13:31:46 -05:00
This child is the parent of another component (C) that defines its own provider for `Car`.
2015-10-17 19:40:10 -04:00
Behind the scenes each component sets up its own injector with one or more providers defined for that component itself.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
When we resolve an instance of `Car` at the deepest component (C),
2015-11-10 13:31:46 -05:00
it's injector produces an instance of `Car` resolved by injector (C) with an `Engine` resolved by injector (B) and
2015-10-17 19:40:10 -04:00
`Tires` resolved by the root injector (A).
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
figure.image-display
2015-12-11 16:18:37 -05:00
img(src="/resources/images/devguide/dependency-injection/injector-tree.png" alt="injector tree" width="600")
2015-10-17 19:40:10 -04:00
2015-11-10 13:31:46 -05:00
.l-main-section
:marked
2015-10-17 19:40:10 -04:00
## Component Injectors
2015-11-10 13:31:46 -05:00
2016-04-23 15:44:09 -04:00
In the previous section, we talked about injectors and how they are organized like a tree. Lookups follow the injector tree upwards until they find the requested thing to inject. But when do we actually want to provide providers on the root injector and when do we want to provide them on a child injector?
2015-11-10 13:31:46 -05:00
Consider you are building a component to show a list of super heroes that displays each super hero in a card with it’ s name and superpower. There should also be an edit button that opens up an editor to change the name and superpower of our hero.
One important aspect of the editing functionality is that we want to allow multiple heroes to be in edit mode at the same time and that one can always either commit or cancel the proposed changes.
Let’ s take a look at the `HeroesListComponent` which is the root component for this example.
2015-12-11 16:18:37 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/heroes-list.component.ts', null, 'app/heroes-list.component.ts')
2015-11-10 13:31:46 -05:00
2015-11-25 12:01:44 -05:00
:marked
2015-10-17 19:40:10 -04:00
Notice that it imports the `HeroService` that we’ ve used before so we can skip its declaration. The only difference is that we’ ve used a more formal approach for our `Hero`model and defined it upfront as such.
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/hero.ts', null, 'app/hero.ts')(format=".")
2015-11-10 13:31:46 -05:00
2015-11-25 12:01:44 -05:00
:marked
2016-04-23 15:44:09 -04:00
Our `HeroesListComponent` defines a template that creates a list of `HeroCardComponent`s and `HeroEditorComponent`s, each bound to an instance of hero that is returned from the `HeroService`. Ok, that’ s not entirely true. It actually binds to an `EditItem<Hero>` which is a simple generic datatype that can wrap any type and indicate if the item being wrapped is currently being edited or not.
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/edit-item.ts', null, 'app/edit-item.ts')(format=".")
2015-11-25 12:01:44 -05:00
:marked
2015-10-17 19:40:10 -04:00
But how is `HeroCardComponent` implemented? Let’ s take a look.
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/hero-card.component.ts', null, 'app/hero-card.component.ts')
2015-11-10 13:31:46 -05:00
2015-11-25 12:01:44 -05:00
:marked
2015-11-10 13:31:46 -05:00
The `HeroCardComponent` is basically a component that defines a template to render a hero. Nothing more.
2015-11-25 12:01:44 -05:00
Let’ s get to the interesting part and take a look at the `HeroEditorComponent`
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/hero-editor.component.ts', null, 'app/hero-editor.component.ts')
2015-11-10 13:31:46 -05:00
2015-11-25 12:01:44 -05:00
:marked
Now here it’ s getting interesting. The `HeroEditorComponent`defines a template with an input to change the name of the hero and a `cancel` and a `save` button. Remember that we said we want to have the flexibility to cancel our editing and restore the old value? This means we need to maintain two copies of our `Hero` that we want to edit. Thinking ahead this is a perfect use case to abstract it into it’ s own generic service since we have probably more cases like this in our app.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
And this is where the `RestoreService` enters the stage.
2015-11-10 13:31:46 -05:00
2016-02-02 17:59:25 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/restore.service.ts', null, 'app/restore.service.ts')
2015-11-10 13:31:46 -05:00
2015-11-25 12:01:44 -05:00
:marked
2015-10-17 19:40:10 -04:00
All this tiny service does is define an API to set a value of any type which can be altered, retrieved or set back to it’ s initial value. That’ s exactly what we need to implement the desired functionality.
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
Our `HeroEditComponent` uses this services under the hood for it’ s `hero` property. It intercepts the `get` and `set` method to delegate the actual work to our `RestoreService` which in turn makes sure that we won’ t work on the original item but on a copy instead.
2015-11-10 13:31:46 -05:00
2016-01-14 05:47:38 -05:00
At this point we may be scratching our heads asking what this has to do with component injectors?
Look closely at the metadata for our `HeroEditComponent`. Notice the `providers` property.
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/hero-editor.component.ts', 'providers')
2015-11-25 12:01:44 -05:00
:marked
2016-01-14 05:47:38 -05:00
This adds a `RestoreService` provider to the injector of the `HeroEditComponent`.
2015-12-11 16:18:37 -05:00
Couldn’ t we simply alter our bootstrap call to this?
2015-11-10 13:31:46 -05:00
2016-01-28 19:15:26 -05:00
+makeExample('hierarchical-dependency-injection/ts/app/main.ts', 'bad-alternative')
2015-12-11 16:18:37 -05:00
:marked
2015-10-17 19:40:10 -04:00
Technically we could, but our component wouldn’ t quite behave the way it is supposed to. Remember that each injector treats the services that it provides as singletons. However, in order to be able to have multiple instances of `HeroEditComponent` edit multiple heroes at the same time we need to have multiple instances of the `RestoreService`. More specifically each instance of `HeroEditComponent` needs to be bound to it’ s own instance of the `RestoreService`.
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
By configuring a provider for the `RestoreService` on the `HeroEditComponent`, we get exactly one new instance of the `RestoreService`per `HeroEditComponent`.
2015-11-10 13:31:46 -05:00
Does that mean that services aren’ t singletons anymore in Angular 2? Yes and no.
2015-12-11 16:18:37 -05:00
There can be only one instance of a service type in a particular injector.
But we've learned that we can have multiple injectors operating at different levels of the application's component tree.
Any of those injectors could have its own instance of the service.
If we defined a `RestoreService` provider only on the root component,
2016-01-14 05:47:38 -05:00
we would have exactly one instance of that service and it would be shared across the entire application.
2015-12-11 16:18:37 -05:00
That’ s clearly not what we want in this scenario. We want each component to have its own instance of the `RestoreService`.
Defining (or re-defining) a provider at the component level creates a new instance of the service for each new instance
2016-01-14 05:47:38 -05:00
of that component. We've made the `RestoreService` a kind of "private" singleton for each `HeroEditComponent`,
2015-12-11 16:18:37 -05:00
scoped to that component instance and its child components.
2015-11-10 13:31:46 -05:00
<!--
2015-10-17 19:40:10 -04:00
## Advanced Dependency Injection in Angular 2
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
Restrict Dependency Lookups
[TODO] (@Host) This has been postponed for now until we come up with a decent use case
2015-11-10 13:31:46 -05:00
2015-10-17 19:40:10 -04:00
.l-main-section
2015-11-10 13:31:46 -05:00
:marked
2015-10-17 19:40:10 -04:00
## Dependency Visibility
2015-11-10 13:31:46 -05:00
2015-12-11 16:18:37 -05:00
[TODO] (providers vs viewProviders) This has been postponed for now until come up with a decent use case
2015-10-17 19:40:10 -04:00
-->