2015-10-17 13:01:41 -04:00
|
|
|
include ../../../../_includes/_util-fns
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
**Dependency Injection** is an important application design pattern.
|
|
|
|
Angular has its own dependency injection framework and
|
2015-10-17 19:40:10 -04:00
|
|
|
we really can't build an Angular application without it.
|
2016-01-11 07:49:12 -05:00
|
|
|
It's used so widely that almost everyone just calls it "DI".
|
|
|
|
|
|
|
|
In this chapter we'll learn [what DI is, why](#why-di) we want it.
|
|
|
|
Then we'll learn [how to use it](#angular-di) in an Angular app.
|
|
|
|
|
|
|
|
All code in this chapter is available as a
|
|
|
|
[live example](/resources/live-examples/dependency-injection/ts/plnkr.html)
|
|
|
|
on the web.
|
|
|
|
|
|
|
|
<a id="why-di"></a>
|
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
|
|
|
## Why Dependency Injection?
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
Let's start with the following code.
|
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
+makeExample('dependency-injection/ts/app/car/car-no-di.ts', 'car', 'app/car/car.ts (no di)')
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
Our `Car` creates everything it needs inside its constructor.
|
|
|
|
What's the problem?
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
The problem is that our `Car` class is brittle, inflexible, and hard to test.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
Our `Car` needs an engine and tires. Instead of asking for them,
|
|
|
|
the `Car` constructor creates its own copies by "new-ing" them from
|
|
|
|
the very specific classes, `Engine` and `Tires`.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
What if the `Engine` class evolves and its constructor requires a parameter?
|
2015-11-10 13:31:46 -05:00
|
|
|
Our `Car` is broken and stays broken until we rewrite it along the lines of
|
|
|
|
`this.engine = new Engine(theNewParameter)`.
|
2015-10-17 19:40:10 -04:00
|
|
|
We didn't care about `Engine` constructor parameters when we first wrote `Car`.
|
2015-11-10 13:31:46 -05:00
|
|
|
We don't really care about them now.
|
|
|
|
But we'll *have* to start caring because
|
2015-10-17 19:40:10 -04:00
|
|
|
when the definion of `Engine` changes, our `Car` class must change.
|
|
|
|
That makes `Car` brittle.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
What if we want to put a different brand of tires on our `Car`. Too bad.
|
2015-10-17 19:40:10 -04:00
|
|
|
We're locked into whatever brand the `Tires` class creates. That makes our `Car` inflexible.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
Right now each new car gets its own engine. It can't share an engine with other cars.
|
|
|
|
While that makes sense for an automobile engine,
|
2015-10-17 19:40:10 -04:00
|
|
|
we can think of other dependencies that should be shared ... like the onboard
|
|
|
|
wireless connection to the manufacturer's service center. Our `Car` lacks the flexibility
|
|
|
|
to share services that have been created previously for other consumers.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
When we write tests for our `Car` we're at the mercy of its hidden dependencies.
|
2015-11-10 13:31:46 -05:00
|
|
|
Is it even possible to create a new `Engine` in a test environment?
|
2015-10-17 19:40:10 -04:00
|
|
|
What does `Engine`itself depend upon? What does that dependency depend on?
|
2015-11-10 13:31:46 -05:00
|
|
|
Will a new instance of `Engine` make an asynchronous call to the server?
|
2015-10-17 19:40:10 -04:00
|
|
|
We certainly don't want that going on during our tests.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
What if our `Car` should flash a warning signal when tire pressure is low.
|
2015-12-30 20:06:52 -05:00
|
|
|
How do we confirm that it actually does flash a warning
|
2015-10-17 19:40:10 -04:00
|
|
|
if we can't swap in low-pressure tires during the test?
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
We have no control over the car's hidden dependencies.
|
2015-10-17 19:40:10 -04:00
|
|
|
When we can't control the dependencies, a class become difficult to test.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
How can we make `Car` more robust, more flexible, and more testable?
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
That's super easy. We probably already know what to do. We change our `Car` constructor to this:
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
<a id="ctor-injection"></a>
|
|
|
|
|
|
|
|
+makeTabs(
|
|
|
|
'dependency-injection/ts/app/car/car.ts, dependency-injection/ts/app/car/car-no-di.ts',
|
|
|
|
'car-ctor, car-ctor',
|
|
|
|
'app/car/car.ts DI (constructor), app/car/car.ts No DI (constructor)')(format=".")
|
|
|
|
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
See what happened? We moved the definition of the dependencies to the constructor.
|
2015-10-17 19:40:10 -04:00
|
|
|
Our `Car` class no longer creates an engine or tires.
|
|
|
|
It just consumes them.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
We also leverage TypeScript's constructor syntax for declaring parameters and properties simultaneously.
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
Now we create a car by passing the engine and tires to the constructor.
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/car/car-creations.ts', 'car-ctor-instantiation', 'Simple Car')(format=".")
|
|
|
|
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
How cool is that?
|
2015-10-17 19:40:10 -04:00
|
|
|
The definition of the engine and tire dependencies are decoupled from the `Car` class itself.
|
|
|
|
We can pass in any kind of engine or tires we like, as long as they
|
|
|
|
conform to the general API requirements of an engine or tires.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
If someone extends the `Engine` class, that is not `Car`'s problem.
|
|
|
|
.l-sub-section
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
The consumer of `Car` has the problem. The consumer must update the car creation code to
|
|
|
|
something like:
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/car/car-creations.ts', 'car-ctor-instantiation-with-param', 'Super Car')(format=".")
|
|
|
|
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
The critical point is this: `Car` itself did not have to change.
|
2015-10-17 19:40:10 -04:00
|
|
|
We'll take care of the consumer's problem soon enough.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
:marked
|
|
|
|
The `Car` class is much easier to test because we are in complete control
|
2015-10-17 19:40:10 -04:00
|
|
|
of its dependencies.
|
|
|
|
We can pass mocks to the constructor that do exactly what we want them to do
|
|
|
|
during each test:
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
+makeExample('dependency-injection/ts/app/car/car-creations.ts', 'car-ctor-instantiation-with-mocks', 'Test Car')(format=".")
|
|
|
|
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
**We just learned what Dependency Injection is**.
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
It's a coding pattern in which a class receives its dependencies from external
|
|
|
|
sources rather than creating them itself.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
Cool! But what about that poor consumer?
|
|
|
|
Anyone who wants a `Car` must now
|
|
|
|
create all three parts: the `Car`, `Engine`, and `Tires`.
|
|
|
|
The `Car` class shed its problems at the consumer's expense.
|
|
|
|
We need something that takes care of assembling these parts for us.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
We could write a giant class to do that:
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/car/car-factory.ts', null, 'app/car/car-factory.ts')
|
|
|
|
|
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
It's not so bad now with only three creation methods.
|
|
|
|
But maintaining it will be hairy as the application grows.
|
|
|
|
This `SuperFactory` is going to become a huge spider web of
|
|
|
|
interdependent factory methods!
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
Wouldn't it be nice if we could simply list the things we want to build without
|
2015-10-17 19:40:10 -04:00
|
|
|
having to define which dependency gets injected into what?
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
This is where the Dependency Injection Framework comes into play.
|
2015-11-10 13:31:46 -05:00
|
|
|
Imagine the framework had something called an `Injector`.
|
2015-10-17 19:40:10 -04:00
|
|
|
We register some classes with this `Injector` and it figures out how to create them.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
When we need a `Car`, we simply ask the `Injector` to get it for us and we're good to go.
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/car/car-injector.ts','injector-call')(format=".")
|
|
|
|
|
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
Everyone wins. The `Car` knows nothing about creating an `Engine` or `Tires`.
|
2015-11-10 13:31:46 -05:00
|
|
|
The consumer knows nothing about creating a `Car`.
|
2015-10-17 19:40:10 -04:00
|
|
|
We don't have a gigantic factory class to maintain.
|
|
|
|
Both `Car` and consumer simply ask for what they need and the `Injector` delivers.
|
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
This is what a **Dependency Injection Framework** is all about.
|
2015-10-17 19:40:10 -04:00
|
|
|
|
2015-11-10 13:31:46 -05:00
|
|
|
Now that we know what Dependency Injection is and appreciate its benefits,
|
2015-10-17 19:40:10 -04:00
|
|
|
let's see how it is implemented in Angular.
|
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="angular-di"></a>
|
2015-10-17 13:01:41 -04:00
|
|
|
.l-main-section
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
## Angular Dependency Injection
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
Angular ships with its own Dependency Injection framework. This framework can also be used
|
2015-11-10 13:31:46 -05:00
|
|
|
as a standalone module by other applications and frameworks.
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
That sounds nice. What does it do for us when building components in Angular?
|
2015-11-10 13:31:46 -05:00
|
|
|
Let's see, one step at a time.
|
|
|
|
|
|
|
|
We'll begin with a simplified version of the `HeroesComponent`
|
2015-10-17 19:40:10 -04:00
|
|
|
that we built in the [The Tour of Heroes](../tutorial/).
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
+makeTabs(
|
|
|
|
`dependency-injection/ts/app/heroes/heroes.component.1.ts,
|
|
|
|
dependency-injection/ts/app/heroes/hero-list.component.1.ts,
|
|
|
|
dependency-injection/ts/app/heroes/hero.ts,
|
|
|
|
dependency-injection/ts/app/heroes/mock-heroes.ts`,
|
|
|
|
'v1,,,',
|
|
|
|
`app/heroes/heroes.component.ts,
|
|
|
|
app/heroes/hero-list.component.ts,
|
|
|
|
app/heroes/hero.ts,
|
|
|
|
app/heroes/mock-heroes.ts`)
|
|
|
|
|
|
|
|
:marked
|
|
|
|
The `HeroesComponent` is the root component of the *Heroes* feature area.
|
|
|
|
It governs all the child components of this area.
|
|
|
|
In our stripped down version there is only one child, `HeroListComponent`,
|
|
|
|
dedicated to displaying a list of heroes.
|
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
Do we really need so many files? Of course not!
|
|
|
|
We're going *beyond* the strictly necessary
|
|
|
|
in order to illustrate patterns that will serve us well in real applications.
|
|
|
|
With each file we can make one or two points rather than crowd them all into one file.
|
|
|
|
:marked
|
|
|
|
Right now it gets heroes from `HEREOES`, an in-memory collection,
|
|
|
|
defined in another file and imported by this component.
|
|
|
|
That may suffice in the early stages of development but it's far from ideal.
|
2015-11-10 13:31:46 -05:00
|
|
|
As soon as we try to test this component or want to get our heroes data from a remote server,
|
2016-01-11 07:49:12 -05:00
|
|
|
we'll have to change the implementation of `heroes` and
|
2015-10-17 19:40:10 -04:00
|
|
|
fix every other use of the `HEROES` mock data.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
Let's make a service that hides how we get hero data.
|
2015-10-17 19:40:10 -04:00
|
|
|
.l-sub-section
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
Write this service in its own file. See [this note](#forward-ref) to understand why.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
+makeExample('dependency-injection/ts/app/heroes/hero.service.1.ts',null, 'app/heroes/hero.service.ts' )
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
Our `HeroService` exposes a `getHeroes()` method that returns
|
|
|
|
the same mock data as before but none of its consumers need to know that.
|
2016-01-11 07:49:12 -05:00
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
We aren't even pretending this is a real service.
|
|
|
|
If we were actually getting data from a remote server, the API would have to be asynchronous,
|
|
|
|
perhaps returning
|
|
|
|
[ES2015 promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
|
|
|
|
We'd also have to rewrite the way components consume our service.
|
|
|
|
This is important but not important to our current story.
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
A service is nothing more than a class in Angular 2.
|
2016-01-11 07:49:12 -05:00
|
|
|
It remains nothing more than a class until we register it with an Angular injector.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
### Configuring the Injector
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="bootstrap"></a>
|
|
|
|
We don't have to create an Angular injector.
|
2015-10-17 19:40:10 -04:00
|
|
|
Angular creates an application-wide injector for us during the bootstrap process.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
+makeExample('dependency-injection/ts/app/main.ts', 'bootstrap', 'app/main.ts (bootstrap)')(format='.')
|
|
|
|
:marked
|
|
|
|
We do have to configure the injector by registering the **providers**
|
|
|
|
that create the services we need in our application.
|
|
|
|
We'll explain what [providers](#providers) are later in this chapter.
|
|
|
|
Before we do, let's see an example of provider registration during bootstrapping:
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/main.1.ts', 'bootstrap')(format='.')
|
|
|
|
:marked
|
|
|
|
The injector now knows about our `HeroService`.
|
|
|
|
An instance of our `HeroService` will be available for injection across our entire application.
|
|
|
|
|
|
|
|
Of course we can't help wondering about that comment telling us not to do it this way.
|
|
|
|
It *will* work. It's just not a best practice.
|
|
|
|
The bootstrap provider option is intended for configuring and overriding Angular's own
|
|
|
|
pre-registered services.
|
|
|
|
|
|
|
|
The preferred approach is to register application providers in application components.
|
|
|
|
Because the `HeroService` will be used within the *Heroes* feature area —
|
|
|
|
and nowhere else — the ideal place to register it is in the top-level `HeroesComponent`.
|
|
|
|
|
|
|
|
### Registering providers in a component
|
|
|
|
Here's a revised `HeroesComponent` that registers the `HeroService`.
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/heroes/heroes.component.1.ts',null,'app/heroes/heroes.component.ts')
|
|
|
|
:marked
|
|
|
|
Look closely at the bottom of the `@Component` metadata:
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/heroes/heroes.component.1.ts','providers')(format='.')
|
|
|
|
:marked
|
|
|
|
An instance of the `HeroService` is now available for injection in this `HeroesComponent`
|
|
|
|
and all of its child components.
|
|
|
|
|
|
|
|
The `HeroesComponent` itself doesn't happen to need the `HeroService`.
|
|
|
|
But its child `HeroListComponent` does so we head there next.
|
|
|
|
|
|
|
|
### Preparing the *HeroListComponent* for injection
|
|
|
|
|
|
|
|
The `HeroListComponent` should get heroes from the injected `HeroService`.
|
2015-10-17 19:40:10 -04:00
|
|
|
Per the dependency injection pattern, the component must "ask for" the service in its constructor [as we explained
|
2016-01-11 07:49:12 -05:00
|
|
|
earlier](#ctor-injection).
|
|
|
|
It's a small change as we see in this comparison:
|
|
|
|
+makeTabs(
|
|
|
|
`dependency-injection/ts/app/heroes/hero-list.component.2.ts,
|
|
|
|
dependency-injection/ts/app/heroes/hero-list.component.1.ts`,
|
|
|
|
null,
|
|
|
|
`app/heroes/hero-list.component (DI),
|
|
|
|
app/heroes/hero-list.component (no DI)`)
|
|
|
|
:marked
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
.l-sub-section
|
2016-01-11 07:49:12 -05:00
|
|
|
:marked
|
|
|
|
### Focus on the constructor
|
|
|
|
+makeExample('dependency-injection/ts/app/heroes/hero-list.component.2.ts', 'ctor')(format=".")
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
Adding a parameter to the constructor isn't all that's happening here.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
We're writing in TypeScript and have followed the parameter name with a type annotation, `:HeroService`.
|
2015-10-17 19:40:10 -04:00
|
|
|
The class is also decorated with the `@Component` decorator (scroll up to confirm that fact).
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
When the TypeScript compiler evaluates this class, it sees the `@Component` decorator and adds class metadata
|
2015-10-17 19:40:10 -04:00
|
|
|
into the generated JavaScript code. Within that metadata lurks the information that
|
2015-11-10 13:31:46 -05:00
|
|
|
associates the `heroService` parameter with the `HeroService` class.
|
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
That's how the Angular injector knows to inject an instance of the `HeroService` when it
|
|
|
|
creates a new `HeroListComponent`.
|
|
|
|
<a id="di-metadata"></a>
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
### Creating the injector (implicitly)
|
2015-10-17 19:40:10 -04:00
|
|
|
When we introduced the idea of an injector above, we showed how to create
|
2016-01-11 07:49:12 -05:00
|
|
|
an injector and use it to create a new `Car`.
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/car/car-injector.ts','injector-create-and-call')(format=".")
|
|
|
|
|
|
|
|
:marked
|
|
|
|
We won't find code like that in the Tour of Heroes or any of our other samples.
|
|
|
|
We *could* write code [like that](#explicit-injector) if we *had* to which we rarely do.
|
|
|
|
Angular takes care of creating and calling injectors
|
|
|
|
when it creates components for us whether through HTML markup, as in `<hero-list></hero-list>`,
|
|
|
|
or after navigating to a component with the [router](./router.html).
|
|
|
|
Let Angular do its job and we'll enjoy the benefits of automated dependency injection.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
### Singleton services
|
2016-01-11 07:49:12 -05:00
|
|
|
Dependencies are singletons within the scope of an injector.
|
|
|
|
In our example, there is a single `HeroService` instance shared among the
|
|
|
|
`HeroesComponent` and its `HeroListComponent` children.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
However, Angular DI is an hierarchical injection
|
|
|
|
system which means nested injectors can create their own service instances.
|
|
|
|
Learn more about that in the [Hierarchical Injection](./hierarchical-dependency-injection.html) chapter.
|
2015-10-17 19:40:10 -04:00
|
|
|
|
|
|
|
### Testing the component
|
2016-01-11 07:49:12 -05:00
|
|
|
We emphasized earlier that designing a class for dependency injection makes the class easier to test.
|
|
|
|
Listing dependencies as constructor parameters may be all we need to test application parts effectively.
|
|
|
|
|
|
|
|
For example, we can create a new `HeroListComponent` with a mock service that we can manipulate
|
|
|
|
under test:
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/test.component.ts', 'spec')(format='.')
|
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
Learn more in the [Testing](../testing/index.html) chapter.
|
|
|
|
|
|
|
|
:marked
|
2015-11-10 13:31:46 -05:00
|
|
|
### When the service needs a service
|
|
|
|
Our `HeroService` is very simple. It doesn't have any dependencies of its own.
|
|
|
|
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
What if it had a dependency? What if it reported its activities through a logging service?
|
2016-01-11 07:49:12 -05:00
|
|
|
We'd apply the same *constructor injection* pattern,
|
|
|
|
adding a constructor that takes a `logger` parameter.
|
|
|
|
|
|
|
|
Here is the revision compared to the original.
|
|
|
|
|
|
|
|
+makeTabs(
|
|
|
|
`dependency-injection/ts/app/heroes/hero.service.2.ts,
|
|
|
|
dependency-injection/ts/app/heroes/hero.service.1.ts`,
|
|
|
|
null,
|
|
|
|
`app/heroes/hero.service (v.2),
|
|
|
|
app/heroes/hero.service (v.1)`)
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
The constructor now asks for an injected instance of a `Logger` and stores it in a private property called `_logger`.
|
|
|
|
We call that property within our `getHeroes()` method when anyone asks for heroes.
|
|
|
|
|
|
|
|
<a id="injectable"></a>
|
|
|
|
### Why *@Injectable*?
|
|
|
|
Notice the `@Injectable()` decoration above the service class.
|
2015-11-10 13:31:46 -05:00
|
|
|
We haven't seen `@Injectable()` before.
|
2016-01-11 07:49:12 -05:00
|
|
|
As it happens, we could have added it to our first version`HeroService`.
|
|
|
|
We didn't bother because we didn't need it then.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
We need it now... now that our service has an injected dependency.
|
2015-11-10 13:31:46 -05:00
|
|
|
We need it because Angular requires constructor parameter metadata in order to inject a `Logger`.
|
2015-10-17 19:40:10 -04:00
|
|
|
As [we mentioned earlier](#di-metadata), TypeScript *only generates metadata for classes that have a decorator*. .
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
.callout.is-helpful
|
|
|
|
header Always add @Injectable()
|
|
|
|
:marked
|
|
|
|
We recommend adding `@Injectable()` to every service class, even those that don't have dependencies
|
|
|
|
and, therefore, do not technically require it. Two reasons:
|
|
|
|
ol(style="font-size:inherit")
|
|
|
|
li <i>Future proofing</i>: no need to remember <code>@Injectable</code> when we add a dependency later.
|
|
|
|
li <i>Consistency</i>: all services follow the same rules and we don't have to wonder why a decorator is missing.
|
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
The `HeroesComponent` has an injected dependency too. Why don't we add `@Injectable()` to the `HeroesComponent`?
|
|
|
|
|
|
|
|
We *can* add it if we really want to. It isn't necessary because the `HeroesComponent` is already decorated with `@Component`.
|
|
|
|
TypeScript generates metadata for *any* class with a decorator and *any* decorator will do.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
.alert.is-critical
|
|
|
|
:marked
|
|
|
|
**Always include the parentheses!** Always call `@Injectable()`.
|
|
|
|
Our application will fail mysteriously if we forget the parentheses.
|
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
|
2016-01-11 07:49:12 -05:00
|
|
|
## Create and register the *Logger* service
|
|
|
|
We're injecting a Logger into our `HeroService`.
|
|
|
|
We have two remaining steps:
|
|
|
|
1. Create the Logger service
|
|
|
|
1. Register it with the application
|
|
|
|
|
|
|
|
The logger service implementation is no big deal.
|
|
|
|
|
|
|
|
+makeExample(
|
|
|
|
'dependency-injection/ts/app/logger.service.ts',null, 'app/logger.service')
|
|
|
|
:marked
|
|
|
|
We're likely to need the same logger service everywhere in our application
|
|
|
|
so we put it at the root level of the application in the `app/` folder and
|
|
|
|
we register it in the `providers` array of the metadata for our application root component, `AppComponent`.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-1', 'app/app.component.ts (providers)')
|
|
|
|
:marked
|
|
|
|
If we forget to register it, Angular will throw an exception when it first needs the logger:
|
|
|
|
code-example(format).
|
|
|
|
EXCEPTION: No provider for Logger! (HeroListComponent -> HeroService -> Logger)
|
|
|
|
:marked
|
|
|
|
That's telling us that the dependency injector couldn't find the *provider* for the logger
|
|
|
|
when it first tried to call the logger — inside the `HeroService` when the `HeroListComponent`
|
|
|
|
was calling for heroes.
|
|
|
|
The *provider* is the subject of our next section.
|
|
|
|
|
|
|
|
But wait! What if the logger is optional?
|
|
|
|
<a id="optional"></a>
|
|
|
|
### Optional dependencies
|
|
|
|
|
|
|
|
Our `HeroService` currently requires a `Logger`. What if we could get by without a logger?
|
|
|
|
We'd use it if we had it, ignore it if we didn't.
|
|
|
|
|
|
|
|
First we import the `@Optional` decorator.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','import-optional')(format='.')
|
|
|
|
:marked
|
|
|
|
Then rewrite the constructor with that decorator to make the logger optional.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','provider-10-ctor')(format='.')
|
|
|
|
:marked
|
|
|
|
Be prepared for a null logger. If we don't register one somewhere up the line,
|
|
|
|
the injector will inject `null`. We have a method that logs. What can we do?
|
|
|
|
|
|
|
|
We could substitute a *do-nothing* logger stub so that our methods continue to work:
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','provider-10-logger')(format='.')
|
|
|
|
:marked
|
|
|
|
Obviously we'd take a more sophisticated approach if the logger were optional
|
|
|
|
elsewhere as well.
|
|
|
|
|
|
|
|
But enough about optional loggers. In our sample application, the `Logger` is required.
|
|
|
|
We must register a `Logger` with the application injector using *providers*
|
|
|
|
as we learn in the next section.
|
|
|
|
|
|
|
|
<a id="providers"></a>
|
|
|
|
.l-main-section
|
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
## Injector Providers
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
A provider *provides* the concrete, runtime version of a dependency value.
|
|
|
|
The injector relies on **providers** to create instances of the services
|
|
|
|
that it injects into components and other services.
|
|
|
|
|
|
|
|
We must register *providers* with the injector or it won't know what to do.
|
|
|
|
|
|
|
|
Earlier we registered the `Logger` service in the `providers` array of the metadata for the `AppComponent` like this:
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-logger')
|
|
|
|
:marked
|
|
|
|
The `providers` array appears to hold service classes (one service class in this example).
|
|
|
|
In reality it holds instances of the [Provider](../api/core/Provider-class.html) class.
|
|
|
|
|
|
|
|
In our example, when the `HeroService` constructor specifies `logger:Logger`, it's expecting
|
|
|
|
something that has the shape and behavior of the `Logger` class.
|
|
|
|
|
|
|
|
There are many ways to *provide* something that has the shape and behavior of a `Logger`.
|
|
|
|
The `Logger` class itself is an obvious and natural provider - it has the right shape and it's designed to be created.
|
|
|
|
But it's not the only way.
|
|
|
|
|
|
|
|
We can configure the injector with alternative providers that can deliver an object that behaves like a `Logger`.
|
|
|
|
We could provide a substitute class. We could provide a logger-like object.
|
|
|
|
We could give it a provider that calls a logger factory function.
|
|
|
|
Any of these approaches might be a good choice under the right circumstances.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
What matters is that the injector has a provider to go to when it needs a `Logger`.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="provide"></a>
|
|
|
|
### The *provide* function
|
|
|
|
|
|
|
|
We wrote the `providers` array like this:
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-1')
|
|
|
|
:marked
|
|
|
|
This is actually a short-hand expression for a provider registration that creates a new instance of the
|
|
|
|
[Provider](/docs/ts/latest/api/core/Provider-class.html) class.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-2')
|
|
|
|
:marked
|
|
|
|
The [provide](../api/core/provide-function.html) function is the more common and friendlier way to create a `Provider`:
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-3')
|
|
|
|
:marked
|
|
|
|
In both approaches — `Provider` class and `provide` function —
|
|
|
|
we supply two arguments.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
The first is the [token](#token) that serves as the key for both locating a dependency value
|
2015-11-10 13:31:46 -05:00
|
|
|
and registering the provider.
|
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
The second is a provider definition object
|
|
|
|
which we think of as a *recipe* for creating the dependency value.
|
2015-10-27 15:57:50 -04:00
|
|
|
There are many ways to create dependency values ... and many ways to write a recipe.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="class-provider"></a>
|
2015-10-17 19:40:10 -04:00
|
|
|
### Alternative Class Providers
|
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
Occasionally we'll ask a different class to provide the service.
|
2015-10-17 19:40:10 -04:00
|
|
|
In this example, we tell the injector
|
2016-01-11 07:49:12 -05:00
|
|
|
to return a `BetterLogger` when something asks for the `Logger`.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-4')
|
|
|
|
:marked
|
|
|
|
### Class provider with dependencies
|
|
|
|
Maybe an `EvenBetterLogger` could display the user name in the log message.
|
|
|
|
This logger gets the user from the injected `UserService`
|
|
|
|
which happens also to be injected at the application level.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','EvenBetterLogger')
|
|
|
|
:marked
|
|
|
|
Configure it like we did `BetterLogger`.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-5')(format=".")
|
|
|
|
:marked
|
|
|
|
### Aliased Class Providers
|
|
|
|
|
|
|
|
Suppose there is an old component that depends upon an `OldLogger` class.
|
|
|
|
`OldLogger` has the same interface as the `NewLogger` but, for some reason,
|
|
|
|
we can't update the old component to use it.
|
|
|
|
|
|
|
|
When the *old* component logs a message with `OldLogger`,
|
|
|
|
we want the one singleton instance of `NewLogger` to handle it instead.
|
|
|
|
|
|
|
|
The dependency injector should inject that singleton instance
|
|
|
|
when a component asks for either the new or the the old logger.
|
|
|
|
The `OldLogger` should be an alias for `NewLogger`.
|
|
|
|
|
|
|
|
We certainly do not want two different `NewLogger` instances in our app.
|
|
|
|
Unfortunately, that's what we get if we try to alias `OldLogger` to `NewLogger` with `useClass`.
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-6a')(format=".")
|
|
|
|
:marked
|
|
|
|
Alias with the `useExisting` option instead.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-6b')(format=".")
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="value-provider"></a>
|
|
|
|
:marked
|
|
|
|
### Value Providers
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
Sometimes it's easier to provide a ready-made object rather than ask the injector to create it from a class.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','silent-logger')(format=".")
|
|
|
|
:marked
|
|
|
|
Then we register a provider with this object playing the logger role via the `useValue` option.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-7')(format=".")
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="factory-provider"></a>
|
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
### Factory Providers
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
Sometimes we need to create the dependent value dynamically,
|
|
|
|
based on information we won't have until the last possible moment.
|
|
|
|
Maybe the information can change.
|
|
|
|
|
|
|
|
Suppose also that the injectable service has no independent access to the source of this information.
|
|
|
|
|
|
|
|
This situation calls for a **factory provider** as we illustrate next.
|
|
|
|
|
|
|
|
Our HeroService should hide *secret* heroes from normal users.
|
|
|
|
Only authorized users should see them.
|
|
|
|
|
|
|
|
Like the `EvenBetterLogger`, the `HeroService` needs a fact about the user.
|
|
|
|
It needs to know if the user is authorized to see secret heroes.
|
|
|
|
That authorization can change during the course of a single application session
|
|
|
|
as when we log in a different user.
|
|
|
|
|
|
|
|
Unlike `EvenBetterLogger`, we can't inject the `UserService` into the `HeroService`.
|
2015-10-17 19:40:10 -04:00
|
|
|
.l-sub-section
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
Why? We don't know either. Stuff like this happens.
|
|
|
|
:marked
|
|
|
|
Instead the `HeroService` constructor takes a boolean flag to control display of secret heroes.
|
|
|
|
+makeExample('dependency-injection/ts/app/heroes/hero.service.ts','internals', 'app/heroes/hero.service.ts (internals)')(format='.')
|
|
|
|
:marked
|
|
|
|
We can inject the `Logger` but we can't inject the boolean `isAuthorized`.
|
|
|
|
We'll have to take over the creation of new instances of this `HeroService` with a factory provider.
|
|
|
|
|
|
|
|
A factory provider needs a factory function:
|
|
|
|
+makeExample('dependency-injection/ts/app/heroes/hero.service.provider.ts','factory', 'app/heroes/hero.service.provider.ts (factory)')(format='.')
|
|
|
|
:marked
|
|
|
|
Although our `HeroService` knows nothing about the `UserService`, our factory function does.
|
|
|
|
|
|
|
|
We inject both the `Logger` and the `UserService` into the factory provider:
|
|
|
|
+makeExample('dependency-injection/ts/app/heroes/hero.service.provider.ts','provider', 'app/heroes/hero.service.provider.ts (provider)')(format='.')
|
|
|
|
:marked
|
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
.l-sub-section
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
The `useFactory` field tells Angular that the provider is a factory function
|
|
|
|
whose implementation is the `heroServiceFactory`.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
The `deps` property is an array of [provider tokens](#token).
|
2015-10-27 15:57:50 -04:00
|
|
|
The `Logger` and `UserService` classes serve as tokens for their own class providers.
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
Notice that we've captured the factory provider in an exported variable, `heroServiceProvider`.
|
|
|
|
This extra step makes it easier for us to register our `HeroService` whereever we need it.
|
|
|
|
|
|
|
|
In our sample, we need it only in the `HeroesComponent`
|
|
|
|
where it replaces the previous `HeroService` registration in the metadata `providers` array:
|
|
|
|
+makeTabs(
|
|
|
|
`dependency-injection/ts/app/heroes/heroes.component.ts,
|
|
|
|
dependency-injection/ts/app/heroes/heroes.component.1.ts`,
|
|
|
|
null,
|
|
|
|
`app/heroes/heroes.component (v.3),
|
|
|
|
app/heroes/heroes.component (v.2)`)
|
|
|
|
|
|
|
|
<a id="token"></a>
|
|
|
|
.l-main-section
|
|
|
|
:marked
|
|
|
|
## Dependency Injection Tokens
|
|
|
|
|
|
|
|
When we register a provider with an injector we associate that provider with a dependency injection token.
|
|
|
|
The injector maintains an internal *token/provider* map that it references when
|
|
|
|
asked for a dependency
|
|
|
|
|
|
|
|
In all previous examples, the dependency value has been a class *instance* and
|
|
|
|
the class *type* served as its own lookup token.
|
|
|
|
Here we get a `HeroService` directly from the injector by supplying the `HeroService` type as the token.
|
|
|
|
+makeExample('dependency-injection/ts/app/injector.component.ts','get-hero-service')(format='.')
|
|
|
|
:marked
|
|
|
|
We have similar good fortune (in typescript) when we write a constructor that requires an injected class-based dependency.
|
|
|
|
We define a constructor parameter with the `HeroService` class type and Angular knows to inject the
|
|
|
|
service associated with that `HeroService` class token:
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','provider-8-ctor')(format=".")
|
|
|
|
:marked
|
|
|
|
This is all especially convenient when we consider that most dependency values are provided by classes.
|
|
|
|
|
|
|
|
### Non-class Dependencies
|
|
|
|
|
|
|
|
What if the dependency value isn't a class?
|
|
|
|
Sometimes the thing we want to inject is a string, a function, or an object.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
Applications often define configuration objects with lots of small facts like the title of the application or the address of a web api endpoint.
|
|
|
|
These configuration objects aren't always instances of a class. They're just objects ... like this one:
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
+makeExample('dependency-injection/ts/app/app.config.ts','config','app/app-config.ts')(format='.')
|
|
|
|
:marked
|
|
|
|
We'd like to make this `config` object available for injection.
|
|
|
|
We know we can register an object with a [Value Provider](#value-provider).
|
|
|
|
But what do we use for the token?
|
|
|
|
We don't have a class to serve as a token. There is no `Config` class.
|
|
|
|
|
|
|
|
// begin Typescript only
|
|
|
|
<a id="interface"></a>
|
|
|
|
:marked
|
|
|
|
The `CONFIG` constant has an interface, `Config`. Unfortunately, we
|
|
|
|
**cannot use an interface as a token**
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-9a-interface')(format=".")
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','provider-9a-ctor-interface')(format=".")
|
|
|
|
:marked
|
|
|
|
It's not Angular's fault. An interface is a TypeScript design-time artifact.
|
|
|
|
It disappears from the generated JavaScript so there is no interface type information for Angular to find at runtime.
|
|
|
|
// end Typescript only
|
|
|
|
<a id="string-token"></a>
|
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
### String tokens
|
2016-01-11 07:49:12 -05:00
|
|
|
Fortunately, we can register any dependency provider with a string token.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-9a')(format=".")
|
|
|
|
:marked
|
|
|
|
Now we inject the configuration object into any constructor that needs it with
|
|
|
|
the help of an `@Inject` decorator to tell Angular how to find the configuration dependency value.
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','provider-9a-ctor')(format=".")
|
|
|
|
:marked
|
|
|
|
|
|
|
|
// begin Typescript only
|
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
Although it plays no role in dependency injection,
|
|
|
|
the `Config` interface supports strongly-typing of the configuration object within the class.
|
|
|
|
:marked
|
|
|
|
// end typescript only
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="opaque-token"></a>
|
|
|
|
:marked
|
|
|
|
### OpaqueToken
|
|
|
|
Alternatively, we could define and use an [OpaqueToken](../api/core/OpaqueToken-class.html)
|
|
|
|
rather than rely on magic strings that may collide with other developers' string choices.
|
|
|
|
|
|
|
|
The definition looks like this:
|
|
|
|
+makeExample('dependency-injection/ts/app/app.config.ts','token')(format='.')
|
|
|
|
:marked
|
|
|
|
Substitute `APP_CONFIG` for the magic string in provider registration and constructor:
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','providers-9b')(format=".")
|
|
|
|
+makeExample('dependency-injection/ts/app/providers.component.ts','provider-9b-ctor')(format=".")
|
|
|
|
:marked
|
|
|
|
Here's how we provide and inject the configuration object in our top-level `AppComponent`.
|
|
|
|
+makeExample('dependency-injection/ts/app/app.component.ts','providers', 'app/app.component.ts (providers)')(format=".")
|
|
|
|
+makeExample('dependency-injection/ts/app/app.component.ts','ctor', 'app/app.component.ts (constructor)')(format=".")
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2016-01-11 07:49:12 -05:00
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
Angular uses `OpaqueTokens` to register all of its non-class dependencies.
|
|
|
|
|
|
|
|
Internally, the `Provider` turns both the string and the class type into an `OpaqueToken`
|
|
|
|
and keys its *token/provider* map with that.
|
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
|
|
|
# Next Steps
|
|
|
|
We learned the basics of Angular Dependency Injection in this chapter.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
|
|
|
The Angular Dependency Injection is more capable than we've described.
|
2015-10-17 19:40:10 -04:00
|
|
|
We can learn more about its advanced features, beginning with its support for
|
2015-11-19 19:59:22 -05:00
|
|
|
nested injectors, in the
|
2016-01-11 07:49:12 -05:00
|
|
|
[Hierarchical Dependency Injection](hierarchical-dependency-injection.html) chapter.
|
|
|
|
|
|
|
|
.l-main-section
|
|
|
|
<a id="explicit-injector"></a>
|
|
|
|
:marked
|
|
|
|
### Appendix: Working with injectors directly
|
|
|
|
We rarely work directly with an injector.
|
|
|
|
Here's an `InjectorComponent` that does.
|
|
|
|
|
|
|
|
+makeExample('dependency-injection/ts/app/injector.component.ts', 'injector',
|
|
|
|
'app/injector.component.ts')
|
|
|
|
:marked
|
|
|
|
Angular injects the component's own `Injector` which the component uses to acquire services.
|
|
|
|
The services themselves are not injected. They're retrieved via the injector.
|
|
|
|
|
|
|
|
The `get` method throws an error if it can't resolve the requested service.
|
|
|
|
We can call `getOptional` instead, which we do in one case
|
|
|
|
to retrieve a service (`ROUS`) that isn't registered with this or any ancestor injector.
|
|
|
|
|
|
|
|
.l-sub-section
|
|
|
|
:marked
|
|
|
|
This technique is an example of the [Service Locator Pattern](https://en.wikipedia.org/wiki/Service_locator_pattern).
|
|
|
|
|
|
|
|
We **avoid** this technique unless we genuinely need it.
|
|
|
|
It encourages a careless grab-bag approach such as we see here.
|
|
|
|
It's difficult to explain, understand, and test.
|
|
|
|
We can't know by inspecting the constructor what this class requires or what it will do.
|
|
|
|
It could acquire services from any ancestor component, not just its own.
|
|
|
|
We're forced to spelunk the implementation and hope for the best.
|
|
|
|
|
|
|
|
Framework developers may take this approach when they
|
|
|
|
must acquire services generically and dynamically.
|
2015-11-10 13:31:46 -05:00
|
|
|
|
2015-10-17 19:40:10 -04:00
|
|
|
.l-main-section
|
2016-01-11 07:49:12 -05:00
|
|
|
<a id="forward-ref"></a>
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2015-10-17 19:40:10 -04:00
|
|
|
### Appendix: Why we recommend one class per file
|
2016-01-11 07:49:12 -05:00
|
|
|
|
|
|
|
Having multiple classes in the same file is confusing and best avoided.
|
|
|
|
Developers expect one class per file. Keep them happy.
|
|
|
|
|
|
|
|
If we scorn this advice and, say,
|
|
|
|
combine our `HeroService` class with the `HeroesComponent` in the same file,
|
|
|
|
**define the component last!**
|
|
|
|
If we define the component before the service,
|
2015-10-17 19:40:10 -04:00
|
|
|
we'll get a runtime null reference error.
|
|
|
|
|
|
|
|
.l-sub-section
|
2015-11-10 13:31:46 -05:00
|
|
|
:marked
|
2016-01-11 07:49:12 -05:00
|
|
|
We actually can define the component first with the help of the `forwardRef()` method as explained
|
|
|
|
in this [blog post](http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular-2.html).
|
|
|
|
But why flirt with trouble?
|
|
|
|
Avoid the problem altogether and define components and services in separate files.
|