Dependency injection is an important application design pattern.
Angular has its own dependency injection framework, and
you really can't build an Angular application without it.
It's used so widely that almost everyone just calls it DI.
This Car needs an engine and tires. Instead of asking for them,
the Car constructor instantiates its own copies from
the very specific classes Engine and Tires.
如果Engine类升级了,它的构造函数要求传入一个参数,这该怎么办?
这个Car类就被破坏了,在把创建引擎的代码重写为this.engine = new Engine(theNewParameter)之前,它都是坏的。
当第一次写Car类时,我们不关心Engine构造函数的参数,现在也不想关心。
但是,当Engine类的定义发生变化时,就不得不在乎了,Car类也不得不跟着改变。
这就会让Car类过于脆弱。
What if the Engine class evolves and its constructor requires a parameter?
That would break the Car class and it would stay broken until you rewrote it along the lines of
this.engine = new Engine(theNewParameter).
The Engine constructor parameters weren't even a consideration when you first wrote Car.
You may not anticipate them even now.
But you'll have to start caring because
when the definition of Engine changes, the Car class must change.
That makes Car brittle.
What if you want to put a different brand of tires on your Car? Too bad.
You're locked into whatever brand the Tires class creates. That makes the
Car class inflexible.
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,
surely you can think of other dependencies that should be shared, such as the onboard
wireless connection to the manufacturer's service center. This Car lacks the flexibility
to share services that have been created previously for other consumers.
When you write tests for Car you're at the mercy of its hidden dependencies.
Is it even possible to create a new Engine in a test environment?
What does Engine depend upon? What does that dependency depend on?
Will a new instance of Engine make an asynchronous call to the server?
You certainly don't want that going on during tests.
What if the Car should flash a warning signal when tire pressure is low?
How do you confirm that it actually does flash a warning
if you can't swap in low-pressure tires during the test?
我们没法控制这辆车背后隐藏的依赖。
当不能控制依赖时,类就会变得难以测试。
You have no control over the car's hidden dependencies.
When you can't control the dependencies, a class becomes difficult to test.
该如何让Car更强壮、有弹性以及可测试?
How can you make Car more robust, flexible, and testable?
答案非常简单。把Car的构造函数改造成使用 DI 的版本:
That's super easy. Change the Car constructor to a version with DI:
public description ='DI';
constructor(public engine:Engine,public tires:Tires){}
public engine:Engine;public tires:Tires;public description ='No DI';
constructor(){this.engine =newEngine();this.tires =newTires();}
See what happened? The definition of the dependencies are
now in the constructor.
The Car class no longer creates an engine or tires.
It just consumes them.
这个例子又一次借助 TypeScript 的构造器语法来同时定义参数和属性。
This example leverages TypeScript's constructor syntax for declaring
parameters and properties simultaneously.
现在,通过往构造函数中传入引擎和轮胎来创建一辆车。
Now you can create a car by passing the engine and tires to the constructor.
// Simple car with 4 cylinders and Flintstone tires.let car =newCar(newEngine(),newTires());
酷!引擎和轮胎这两个依赖的定义与Car类本身解耦了。
只要喜欢,可以传入任何类型的引擎或轮胎,只要它们能满足引擎或轮胎的通用 API 需求。
How cool is that?
The definition of the engine and tire dependencies are
decoupled from the Car class.
You can pass in any kind of engine or tires you like, as long as they
conform to the general API requirements of an engine or tires.
这样一来,如果有人扩展了Engine类,那就不再是Car类的烦恼了。
Now, if someone extends the Engine class, that is not Car's problem.
Car的消费者也有这个问题。消费者必须更新创建这辆车的代码,就像这样:
The consumer of Car has the problem. The consumer must update the car creation code to
something like this:
classEngine2{
constructor(public cylinders: number){}}// Super car with 12 cylinders and Flintstone tires.let bigCylinders =12;let car =newCar(newEngine2(bigCylinders),newTires());
这里的要点是:Car本身不必变化。下面就来解决消费者的问题。
The critical point is this: the Car class did not have to change.
You'll take care of the consumer's problem shortly.
The Car class is much easier to test now because you are in complete control
of its dependencies.
You can pass mocks to the constructor that do exactly what you want them to do
during each test:
classMockEngineextendsEngine{ cylinders =8;}classMockTiresextendsTires{ make ='YokoGoodStone';}// Test car with 8 cylinders and YokoGoodStone tires.let car =newCar(newMockEngine(),newMockTires());
刚刚学习了什么是依赖注入
You just learned what dependency injection is.
它是一种编程模式,可以让类从外部源中获得它的依赖,而不必亲自创建它们。
It's a coding pattern in which a class receives its dependencies from external
sources rather than creating them itself.
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.
You need something that takes care of assembling these parts.
可以写一个巨型类来做这件事:
You could write a giant class to do that:
src/app/car/car-factory.ts
import{Engine,Tires,Car}from'./car';
// BAD pattern!
exportclassCarFactory{
createCar(){
let car =newCar(this.createEngine(),this.createTires());
It's not so bad now with only three creation methods.
But maintaining it will be hairy as the application grows.
This factory is going to become a huge spiderweb of
interdependent factory methods!
如果能简单的列出想建造的东西,而不用定义该把哪些依赖注入到哪些对象中,那该多好!
Wouldn't it be nice if you could simply list the things you want to build without
having to define which dependency gets injected into what?
This is where the dependency injection framework comes into play.
Imagine the framework had something called an injector.
You register some classes with this injector, and it figures out how to create them.
当需要一个Car时,就简单的找注入器取车就可以了。
When you need a Car, you simply ask the injector to get it for you and you're good to go.
Everyone wins. The Car knows nothing about creating an Engine or Tires.
The consumer knows nothing about creating a Car.
You don't have a gigantic factory class to maintain.
Both Car and consumer simply ask for what they need and the injector delivers.
这就是“依赖注入框架”存在的原因。
This is what a dependency injection framework is all about.
现在,我们知道了什么是依赖注入,以及它的优点。再来看看它在 Angular 中是怎么实现的。
Now that you know what dependency injection is and appreciate its benefits,
read on to see how it is implemented in Angular.
Angular 依赖注入
Angular dependency injection
Angular 附带了自己的依赖注入框架。此框架也能被当做独立模块用于其它应用和框架中。
Angular ships with its own dependency injection framework. This framework can also be used
as a standalone module by other applications and frameworks.
The HeroesComponent is the root component of the Heroes feature area.
It governs all the child components of this area.
This stripped down version has only one child, HeroListComponent,
which displays a list of heroes.
Right now HeroListComponent gets heroes from HEROES, an in-memory collection
defined in another file.
That may suffice in the early stages of development, but it's far from ideal.
As soon as you try to test this component or want to get your heroes data from a remote server,
you'll have to change the implementation of heroes and
fix every other use of the HEROES mock data.
最好用一个服务把获取英雄数据的代码封装起来。
It's better to make a service that hides how the app gets hero data.
The @Injectable() decorator above the service class is
covered shortly.
我们甚至没有假装这是一个真实的服务。
如果真的从远端服务器获取数据,这个 API 必须是异步的,可能得返回
ES2015 承诺 (promise)。
需要重新处理组件消费该服务的方式。通常这个很重要,但是目前的故事不需要。
Of course, this isn't a real service.
If the app were actually getting data from a remote server, the API would have to be
asynchronous, perhaps returning a Promise.
You'd also have to rewrite the way components consume the service.
This is important in general, but not in this example.
服务只是 Angular 中的一个类。
有 Angular 注入器注册它之前,没有任何特别之处。
A service is nothing more than a class in Angular.
It remains nothing more than a class until you register it with an Angular injector.
配置注入器
Configuring the injector
不需要创建 Angular 注入器。
Angular 在启动过程中自动为我们创建一个应用级注入器。
You don't have to create an Angular injector.
Angular creates an application-wide injector for you during the bootstrap process.
You do have to configure the injector by registering the providers
that create the services the application requires.
This guide explains what providers are later.
Because the HeroService is used only within the HeroesComponent
and its subcomponents, the top-level HeroesComponent is the ideal
place to register it.
On the one hand, a provider in an NgModule is registered in the root injector. That means that every provider
registered within an NgModule will be accessible in the entire application.
另一方面,在应用组件中注册的提供商只在该组件及其子组件中可用。
On the other hand, a provider registered in an application component is available only on that component and all its children.
Here, the APP_CONFIG service needs to be available all across the application, so it's
registered in the AppModule@NgModuleproviders array.
But since the HeroService is only used within the Heroes
feature area and nowhere else, it makes sense to register it in
the HeroesComponent.
The HeroListComponent should get heroes from the injected HeroService.
Per the dependency injection pattern, the component must ask for the service in its
constructor, as discussed earlier.
It's a small change:
import{Component}from'@angular/core';
import{Hero}from'./hero';
import{HeroService}from'./hero.service';
@Component({
selector:'hero-list',
template:`
<div *ngFor="let hero of heroes">
{{hero.id}} - {{hero.name}}
</div>
`
})
exportclassHeroListComponent{
heroes:Hero[];
constructor(heroService:HeroService){
this.heroes = heroService.getHeroes();
}
}
import{Component}from'@angular/core';
import{ HEROES }from'./mock-heroes';
@Component({
selector:'hero-list',
template:`
<div *ngFor="let hero of heroes">
{{hero.id}} - {{hero.name}}
</div>
`
})
exportclassHeroListComponent{
heroes = HEROES;
}
来看看构造函数
Focus on the constructor
往构造函数中添加参数并不是这里所发生的一切。
Adding a parameter to the constructor isn't all that's happening here.
Note that the constructor parameter has the type HeroService, and that
the HeroListComponent class has an @Component decorator
(scroll up to confirm that fact).
Also recall that the parent component (HeroesComponent)
has providers information for HeroService.
The constructor parameter type, the @Component decorator,
and the parent's providers information combine to tell the
Angular injector to inject an instance of
HeroService whenever it creates a new HeroListComponent.
隐式注入器的创建
Implicit injector creation
本章前面的部分我们看到了如何使用注入器来创建一个新Car。
你可以像这样显式创建注入器:
You saw how to use an injector to create a new
Car earlier in this guide.
You could create such an injector
explicitly:
injector =ReflectiveInjector.resolveAndCreate([Car,Engine,Tires]);let car = injector.get(Car);
You won't find code like that in the Tour of Heroes or any of the other
documentation samples.
You could write code that explicitly creates an injector if you had to,
but it's not always the best choice.
Angular takes care of creating and calling injectors
when it creates components for you—whether through HTML markup, as in <hero-list></hero-list>,
or after navigating to a component with the router.
If you let Angular do its job, you'll enjoy the benefits of automated dependency injection.
Dependencies are singletons within the scope of an injector.
In this guide's example, a single HeroService instance is shared among the
HeroesComponent and its HeroListComponent children.
然而,Angular DI 是一个分层的依赖注入系统,这意味着嵌套的注入器可以创建它们自己的服务实例。
要了解更多知识,参见多级依赖注入器一章。
However, Angular DI is a hierarchical injection
system, which means that nested injectors can create their own service instances.
For more information, see Hierarchical Injectors.
Earlier you saw that designing a class for dependency injection makes the class easier to test.
Listing dependencies as constructor parameters may be all you need to test application parts effectively.
What if it had a dependency? What if it reported its activities through a logging service?
You'd apply the same constructor injection pattern,
adding a constructor that takes a Logger parameter.
The constructor now asks for an injected instance of a Logger and stores it in a private property called logger.
You call that property within the getHeroes() method when anyone asks for heroes.
@Injectable() marks a class as available to an
injector for instantiation. Generally speaking, an injector reports an
error when trying to instantiate a class that is not marked as
@Injectable().
As it happens, you could have omitted @Injectable() from the first
version of HeroService because it had no injected parameters.
But you must have it now that the service has an injected dependency.
You need it because Angular requires constructor parameter metadata
in order to inject a Logger.
建议:为每个服务类都添加 @Injectable()Suggestion: add @Injectable() to every service class
建议为每个服务类都添加@Injectable(),包括那些没有依赖严格来说并不需要它的。因为:
Consider adding @Injectable() to every service class, even those that don't have dependencies
and, therefore, do not technically require it. Here's why:
面向未来: 没有必要记得在后来添加依赖的时候添加 @Injectable()。
Future proofing: No need to remember @Injectable() when you add a dependency later.
一致性:所有的服务都遵循同样的规则,不需要考虑为什么某个地方少了一个。
Consistency: All services follow the same rules, and you don't have to wonder why a decorator is missing.
You can add it if you really want to. It isn't necessary because the
HeroesComponent is already marked with @Component, and this
decorator class (like @Directive and @Pipe, which you learn about later)
is a subtype of @Injectable(). It is in
fact @Injectable() decorators that
identify a class as a target for instantiation by an injector.
At runtime, injectors can read class metadata in the transpiled JavaScript code
and use the constructor parameter type information
to determine what things to inject.
Not every JavaScript class has metadata.
The TypeScript compiler discards metadata by default.
If the emitDecoratorMetadata compiler option is true
(as it should be in the tsconfig.json),
the compiler adds the metadata to the generated JavaScript
for every class with at least one decorator.
You're likely to need the same logger service everywhere in your application,
so put it in the project's app folder and
register it in the providers array of the application module, AppModule.
src/app/app.module.ts (excerpt)
providers:[Logger]
如果忘了注册这个日志服务,Angular 会在首次查找这个日志服务时,抛出一个异常。
If you forget to register the logger, Angular throws an exception when it first looks for the logger:
EXCEPTION: No provider for Logger! (HeroListComponent -> HeroService -> Logger)
(异常:Logger类没有提供商!(HeroListComponent -> HeroService -> Logger))
That's Angular telling you that the dependency injector couldn't find the provider for the logger.
It needed that provider to create a Logger to inject into a new
HeroService, which it needed to
create and inject into a new HeroListComponent.
这个“创建链”始于Logger的提供商。这个提供商就是下一节的主题 。
The chain of creations started with the Logger provider. Providers are the subject of the next section.
A provider provides the concrete, runtime version of a dependency value.
The injector relies on providers to create instances of the services
that the injector injects into components and other services.
必须为注入器注册一个服务的提供商,否则它不知道该如何创建该服务。
You must register a service provider with the injector, or it won't know how to create the service.
我们在前面通过AppModule元数据中的providers数组注册过Logger服务,就像这样:
Earlier you registered the Logger service in the providers array of the metadata for the AppModule like this:
There are many ways to provide something that looks and behaves like a Logger.
The Logger class itself is an obvious and natural provider.
But it's not the only way.
You can configure the injector with alternative providers that can deliver an object that behaves like a Logger.
You could provide a substitute class. You could provide a logger-like object.
You could give it a provider that calls a logger factory function.
Any of these approaches might be a good choice under the right circumstances.
最重要的是,当注入器需要一个Logger时,它得先有一个提供商。
What matters is that the injector has a provider to go to when it needs a Logger.
Provider类和一个提供商的字面量
The Provider class and provide object literal
像下面一样写providers数组:
You wrote the providers array like this:
providers:[Logger]
这其实是用于注册提供商的简写表达式。
使用的是一个带有两个属性的提供商对象字面量:
This is actually a shorthand expression for a provider registration
using a provider object literal with two properties:
The second is a provider definition object,
which you can think of as a recipe for creating the dependency value.
There are many ways to create dependency values just as there are many ways to write a recipe.
Occasionally you'll ask a different class to provide the service.
The following code tells the injector
to return a BetterLogger when something asks for the Logger.
Maybe an EvenBetterLogger could display the user name in the log message.
This logger gets the user from the injected UserService,
which is also injected at the application level.
@Injectable()classEvenBetterLoggerextendsLogger{
constructor(private userService:UserService){super();}
log(message:string){let name =this.userService.user.name;super.log(`Message to ${name}: ${message}`);}}
Suppose an old component depends upon an OldLogger class.
OldLogger has the same interface as the NewLogger, but for some reason
you can't update the old component to use it.
当旧组件想使用OldLogger记录消息时,我们希望改用NewLogger的单例对象来记录。
When the old component logs a message with OldLogger,
you'd like the 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 old logger.
The OldLogger should be an alias for NewLogger.
You certainly do not want two different NewLogger instances in your app.
Unfortunately, that's what you get if you try to alias OldLogger to NewLogger with useClass.
[NewLogger,// Not aliased! Creates two instances of `NewLogger`{ provide:OldLogger, useClass:NewLogger}]
解决方案:使用useExisting选项指定别名。
The solution: alias with the useExisting option.
[NewLogger,// Alias OldLogger w/ reference to NewLogger{ provide:OldLogger, useExisting:NewLogger}]
值提供商
Value providers
有时,提供一个预先做好的对象会比请求注入器从类中创建它更容易。
Sometimes it's easier to provide a ready-made object rather than ask the injector to create it from a class.
// An object in the shape of the logger servicelet silentLogger ={
logs:['Silent logger says "Shhhhh!". Provided via "useValue"'],
log:()=>{}};
于是可以通过useValue选项来注册提供商,它会让这个对象直接扮演 logger 的角色。
Then you register a provider with the useValue option,
which makes this object play the logger role.
Sometimes you need to create the dependent value dynamically,
based on information you won't have until the last possible moment.
Maybe the information changes repeatedly in the course of the browser session.
还假设这个可注入的服务没法通过独立的源访问此信息。
Suppose also that the injectable service has no independent access to the source of this information.
To illustrate the point, add a new business requirement:
the HeroService must hide secret heroes from normal users.
Only authorized users should see secret heroes.
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 you log in a different user.
Unlike EvenBetterLogger, you can't inject the UserService into the HeroService.
The HeroService won't have direct access to the user information to decide
who is authorized and who is not.
让HeroService的构造函数带上一个布尔型的标志,来控制是否显示隐藏的英雄。
Instead, the HeroService constructor takes a boolean flag to control display of secret heroes.
You can inject the Logger, but you can't inject the boolean isAuthorized.
You'll have to take over the creation of new instances of this HeroService with a factory provider.
工厂提供商需要一个工厂方法:
A factory provider needs a factory function:
src/app/heroes/hero.service.provider.ts (excerpt)
let heroServiceFactory =(logger:Logger, userService:UserService)=>{returnnewHeroService(logger, userService.user.isAuthorized);};
虽然HeroService不能访问UserService,但是工厂方法可以。
Although the HeroService has no access to the UserService, the factory function does.
同时把Logger和UserService注入到工厂提供商中,并且让注入器把它们传给工厂方法:
You inject both the Logger and the UserService into the factory provider
and let the injector pass them along to the factory function:
The deps property is an array of provider tokens.
The Logger and UserService classes serve as tokens for their own class providers.
The injector resolves these tokens and injects the corresponding services into the matching factory function parameters.
Notice that you captured the factory provider in an exported variable, heroServiceProvider.
This extra step makes the factory provider reusable.
You can register the HeroService with this variable wherever you need it.
In this sample, you need it only in the HeroesComponent,
where it replaces the previous HeroService registration in the metadata providers array.
Here you see the new and the old implementation side-by-side:
当向注入器注册提供商时,实际上是把这个提供商和一个 DI 令牌关联起来了。
注入器维护一个内部的令牌-提供商映射表,这个映射表会在请求依赖时被引用到。
令牌就是这个映射表中的键值。
When you register a provider with an injector, you associate that provider with a dependency injection token.
The injector maintains an internal token-provider map that it references when
asked for a dependency. The token is the key to the map.
In all previous examples, the dependency value has been a class instance, and
the class type served as its own lookup key.
Here you get a HeroService directly from the injector by supplying the HeroService type as the token:
You have similar good fortune when you write a constructor that requires an injected class-based dependency.
When you define a constructor parameter with the HeroService class type,
Angular knows to inject the
service associated with that HeroService class token:
constructor(heroService:HeroService)
这是一个特殊的规约,因为大多数依赖值都是以类的形式提供的。
This is especially convenient when you consider that most dependency values are provided by classes.
非类依赖
Non-class dependencies
如果依赖值不是一个类呢?有时候想要注入的东西是一个字符串,函数或者对象。
What if the dependency value isn't a class? Sometimes the thing you want to inject is a
string, function, or object.
Applications often define configuration objects with lots of small facts
(like the title of the application or the address of a web API endpoint)
but these configuration objects aren't always instances of a class.
They can be object literals such as this one:
It's not Angular's doing. An interface is a TypeScript design-time artifact. JavaScript doesn't have interfaces.
The TypeScript interface disappears from the generated JavaScript.
There is no interface type information left for Angular to find at runtime.
One solution to choosing a provider token for non-class dependencies is
to define and use an InjectionToken.
The definition of such a token looks like this:
The HeroServicerequires a Logger, but what if it could get by without
a logger?
You can tell Angular that the dependency is optional by annotating the
constructor argument with @Optional():
When using @Optional(), your code must be prepared for a null value. If you
don't register a logger somewhere up the line, the injector will set the
value of logger to null.
You learned the basics of Angular dependency injection in this page.
You can register various kinds of providers,
and you know how to ask for an injected object (such as a service) by
adding a parameter to a constructor.
Angular dependency injection is more capable than this guide has described.
You can learn more about its advanced features, beginning with its support for
nested injectors, in
Hierarchical Dependency Injection.
附录:直接使用注入器
Appendix: Working with injectors directly
这里的InjectorComponent直接使用了注入器,
但我们很少直接使用它。
Developers rarely work directly with an injector, but
here's an InjectorComponent that does.
In this example, Angular injects the component's own Injector into the component's constructor.
The component then asks the injected injector for the services it wants in ngOnInit().
注意,这些服务本身没有注入到组件,它们是通过调用injector.get()获得的。
Note that the services themselves are not injected into the component.
They are retrieved by calling injector.get().
The get() method throws an error if it can't resolve the requested service.
You can call get() with a second parameter, which is the value to return if the service
is not found. Angular can't find the service if it's not registered with this or any ancestor injector.
Avoid this technique unless you genuinely need it.
It encourages a careless grab-bag approach such as you see here.
It's difficult to explain, understand, and test.
You 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.
You're forced to spelunk the implementation to discover what it does.
框架开发人员必须采用通用的或者动态的方式获取服务时,可能采用这个方法。
Framework developers may take this approach when they
must acquire services generically and dynamically.
附录:为什么建议每个文件只放一个类
Appendix: Why have one class per file
在同一个文件中有多个类容易造成混淆,最好避免。
开发人员期望每个文件只放一个类。这会让它们开心点。
Having multiple classes in the same file is confusing and best avoided.
Developers expect one class per file. Keep them happy.
If you combine the HeroService class with
the HeroesComponent in the same file,
define the component last.
If you define the component before the service,
you'll get a runtime null reference error.
You actually can define the component first with the help of the forwardRef() method as explained
in this blog post.
But why flirt with trouble?
Avoid the problem altogether by defining components and services in separate files.