依赖注入

Dependency injection is an important application design pattern. Angular has its own dependency injection framework, and we really can't build an Angular application without it. It's used so widely that almost everyone just calls it DI.

依赖注入是重要的程序设计模式。 Angular 有自己的依赖注入框架,离开了它,几乎没法构建 Angular 应用。 它使用得非常广泛,以至于几乎每个人都会把它简称为 DI

In this chapter we'll learn what DI is and why we want it. Then we'll learn how to use it in an Angular app.

本章将学习什么是 DI,以及为什么需要它。 然后,将学习在 Angular 应用中该如何使用它

Run the .

运行在线例子.

Why dependency injection?

为什么需要依赖注入?

Let's start with the following code.

我们从下列代码开始:

src/app/car/car.ts (without DI)

export class Car { public engine: Engine; public tires: Tires; public description = 'No DI'; constructor() { this.engine = new Engine(); this.tires = new Tires(); } // Method using the engine and tires drive() { return `${this.description} car with ` + `${this.engine.cylinders} cylinders and ${this.tires.make} tires.`; } }

Our Car creates everything it needs inside its constructor. What's the problem?

Car类会在它的构造函数中创建所需的每样东西。 问题何在?

The problem is that our Car class is brittle, inflexible, and hard to test.

问题在于,这个Car类过于脆弱、缺乏弹性并且难以测试。

Our 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.

Car类需要一个引擎 (engine) 和一些轮胎 (tire),它没有去请求现成的实例, 而是在构造函数中用具体的EngineTires类实例化出自己的副本。

What if the Engine class evolves and its constructor requires a parameter? Our Car is broken and stays broken until we rewrite it along the lines of this.engine = new Engine(theNewParameter). We didn't care about Engine constructor parameters when we first wrote Car. We don't really care about them now. But we'll have to start caring because when the definition of Engine changes, our Car class must change. That makes Car brittle.

如果Engine类升级了,它的构造函数要求传入一个参数,这该怎么办? 这个Car类就被破坏了,在把创建引擎的代码重写为engine = new Engine(theNewParameter)之前,它都是坏的。 当第一次写Car类时,我们不关心Engine构造函数的参数,现在也不想关心。 但是,当Engine类的定义发生变化时,就不得不在乎了,Car类也不得不跟着改变。 这就会让Car类过于脆弱。

What if we want to put a different brand of tires on our Car? Too bad. We're locked into whatever brand the Tires class creates. That makes our Car inflexible.

如果想在Car上使用不同品牌的轮胎会怎样?太糟了。 我们被锁定在Tires类创建时使用的那个品牌上。这让Car类缺乏弹性。

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, we can think of other dependencies that should be shared, such as 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.

现在,每辆车都有它自己的引擎。它不能和其它车辆共享引擎。 虽然这对于汽车来说还算可以理解,但是设想一下那些应该被共享的依赖,比如用来联系厂家服务中心的车载无线电。 我们的车缺乏必要的弹性,无法共享当初给其它消费者创建的车载无线电。

When we write tests for our Car we're at the mercy of its hidden dependencies. Is it even possible to create a new Engine in a test environment? What does Engineitself depend upon? What does that dependency depend on? Will a new instance of Engine make an asynchronous call to the server? We certainly don't want that going on during our tests.

当给Car类写测试的时候,我们被它那些隐藏的依赖所摆布。 能在测试环境中成功创建新的Engine吗? Engine自己又依赖什么?那些依赖本身又依赖什么? Engine的新实例会发起到服务器的异步调用吗? 我们当然不想在测试期间这么一层层追下去。

What if our Car should flash a warning signal when tire pressure is low? How do we confirm that it actually does flash a warning if we can't swap in low-pressure tires during the test?

如果Car应该在轮胎气压低的时候闪动警示灯该怎么办? 如果没法在测试期间换上一个低气压的轮胎,那该如何确认它能正确的闪警示灯?

We have no control over the car's hidden dependencies. When we can't control the dependencies, a class becomes difficult to test.

我们没法控制这辆车背后隐藏的依赖。 当不能控制依赖时,类就会变得难以测试。

How can we make Car more robust, flexible, and testable?

该如何让Car更强壮、有弹性以及可测试?

That's super easy. We change our Car constructor to a version with DI:

答案超级简单。把Car的构造函数改造成使用 DI 的版本:

public description = 'DI'; constructor(public engine: Engine, public tires: Tires) { } public engine: Engine; public tires: Tires; public description = 'No DI'; constructor() { this.engine = new Engine(); this.tires = new Tires(); }

See what happened? We moved the definition of the dependencies to the constructor. Our Car class no longer creates an engine or tires. It just consumes them.

发生了什么?我们把依赖的定义移到了构造函数中。 Car类不再创建引擎或者轮胎。 它仅仅“消费”它们。

We also leveraged TypeScript's constructor syntax for declaring parameters and properties simultaneously.

再次借助 TypeScript 的构造器语法来同时定义参数和属性。

Now we create a car by passing the engine and tires to the constructor.

现在,通过往构造函数中传入引擎和轮胎来创建一辆车。

// Simple car with 4 cylinders and Flintstone tires. let car = new Car(new Engine(), new Tires());

How cool is that? 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.

酷!引擎和轮胎这两个依赖的定义与Car类本身解耦了。 只要喜欢,可以传入任何类型的引擎或轮胎,只要它们能满足引擎或轮胎的通用 API 需求。

If someone extends the Engine class, that is not Car's problem.

如果有人扩展了Engine类,那就不再是Car类的烦恼了。

The consumer of Car has the problem. The consumer must update the car creation code to something like this:

Car消费者也有这个问题。消费者必须更新创建这辆车的代码,就像这样:

class Engine2 { constructor(public cylinders: number) { } } // Super car with 12 cylinders and Flintstone tires. let bigCylinders = 12; let car = new Car(new Engine2(bigCylinders), new Tires());

The critical point is this: Car itself did not have to change. We'll take care of the consumer's problem soon enough.

这里的要点是:Car本身不必变化。下面就来解决消费者的问题。

The Car class is much easier to test because we are in complete control of its dependencies. We can pass mocks to the constructor that do exactly what we want them to do during each test:

Car类非常容易测试,因为现在我们对它的依赖有了完全的控制权。 在每个测试期间,我们可以往构造函数中传入 mock 对象,做想让它们做的事:

class MockEngine extends Engine { cylinders = 8; } class MockTires extends Tires { make = 'YokoGoodStone'; } // Test car with 8 cylinders and YokoGoodStone tires. let car = new Car(new MockEngine(), new MockTires());

We 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. We need something that takes care of assembling these parts for us.

酷!但是,可怜的消费者怎么办? 那些希望得到一个Car的人们现在必须创建所有这三部分了:CarEngineTiresCar类把它的快乐建立在了消费者的痛苦之上。 需要某种机制为我们把这三个部分装配好。

We could write a giant class to do that:

可以写一个巨型类来做这件事:

src/app/car/car-factory.ts

import { Engine, Tires, Car } from './car'; // BAD pattern! export class CarFactory { createCar() { let car = new Car(this.createEngine(), this.createTires()); car.description = 'Factory'; return car; } createEngine() { return new Engine(); } createTires() { return new Tires(); } }

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 we could simply list the things we 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. We register some classes with this injector, and it figures out how to create them.

到了依赖注入框架一展身手的时候了! 想象框架中有一个叫做注入器 (injector) 的东西。 用这个注入器注册一些类,它会弄明白如何创建它们。

When we need a Car, we simply ask the injector to get it for us and we're good to go.

当需要一个Car时,就简单的找注入器取车就可以了。

let car = injector.get(Car);

Everyone wins. The Car knows nothing about creating an Engine or Tires. The consumer knows nothing about creating a Car. We don't have a gigantic factory class to maintain. Both Car and consumer simply ask for what they need and the injector delivers.

皆大欢喜。Car不需要知道如何创建EngineTires。 消费者不需要知道如何创建Car。 开发人员不需要维护巨大的工厂类。 Car和消费者只要简单地请求想要什么,注入器就会交付它们。

This is what a dependency injection framework is all about.

这就是“依赖注入框架”存在的原因。

Now that we know what dependency injection is and appreciate its benefits, let's 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.

Angular 附带了自己的依赖注入框架。此框架也能被当做独立模块用于其它应用和框架中。

That sounds nice. What does it do for us when building components in Angular? Let's see, one step at a time.

听起来很好。当在 Angular 中构建组件的时候,它到底能为我们做了什么呢? 来一点一点搞清楚吧。

We'll begin with a simplified version of the HeroesComponent that we built in the The Tour of Heroes.

英雄指南中构建的HeroesComponent的简化版本开始。

import { Component } from '@angular/core'; @Component({ selector: 'my-heroes', template: ` <h2>Heroes</h2> <hero-list></hero-list> ` }) export class HeroesComponent { } 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> ` }) export class HeroListComponent { heroes = HEROES; } export class Hero { id: number; name: string; isSecret = false; } import { Hero } from './hero'; export var HEROES: Hero[] = [ { id: 11, isSecret: false, name: 'Mr. Nice' }, { id: 12, isSecret: false, name: 'Narco' }, { id: 13, isSecret: false, name: 'Bombasto' }, { id: 14, isSecret: false, name: 'Celeritas' }, { id: 15, isSecret: false, name: 'Magneta' }, { id: 16, isSecret: false, name: 'RubberMan' }, { id: 17, isSecret: false, name: 'Dynama' }, { id: 18, isSecret: true, name: 'Dr IQ' }, { id: 19, isSecret: true, name: 'Magma' }, { id: 20, isSecret: true, name: 'Tornado' } ];

The HeroesComponent is the root component of the Heroes feature area. It governs all the child components of this area. Our stripped down version has only one child, HeroListComponent, which displays a list of heroes.

HeroesComponent英雄特性区域的根组件。它管理区域内所有子组件。 简化后的版本只有一个子组件HeroListComponent,用来显示英雄列表。

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 we try to test this component or want to get our heroes data from a remote server, we'll have to change the implementation of heroes and fix every other use of the HEROES mock data.

现在HeroListComponentHEROES获得英雄数据,是在另一个文件中定义的内存数据集。 它在开发的早期阶段可能还够用,但离完美就差得远了。 一旦开始测试此组件,或者想从远端服务器获得英雄数据,就不得不修改heroes的实现, 还要修改每个用到了HEROES模拟数据的地方。

Let's make a service that hides how we get hero data.

可以用一个服务把获取英雄数据的代码封装起来。

Given that the service is a separate concern, we suggest that you write the service code in its own file.

因为服务是一个分离关注点, 建议你把服务代码放到它自己的文件里。

See this note for details.

更多信息,见这个笔记

src/app/heroes/hero.service.ts

import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; @Injectable() export class HeroService { getHeroes() { return HEROES; } }

Our HeroService exposes a getHeroes method that returns the same mock data as before, but none of its consumers need to know that.

HeroService暴露了getHeroes方法,返回跟以前一样的模拟数据,但它的消费者不需要知道这一点。

Notice the @Injectable() decorator above the service class. We'll discuss its purpose shortly.

注意服务类上面这个@Injectable()装饰器。很快会讨论它的用途。

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 a Promise. We'd also have to rewrite the way components consume our service. This is important in general, but not to our current story.

我们甚至没有假装这是一个真实的服务。 如果真的从远端服务器获取数据,这个 API 必须是异步的,可能得返回 ES2015 承诺 (promise)。 需要重新处理组件消费该服务的方式。通常这个很重要,但是目前的故事不需要。

A service is nothing more than a class in Angular. It remains nothing more than a class until we register it with an Angular injector.

服务只是 Angular 中的一个类。 有 Angular 注入器注册它之前,没有任何特别之处。

Configuring the injector

配置注入器

We don't have to create an Angular injector. Angular creates an application-wide injector for us during the bootstrap process.

不需要创建 Angular 注入器。 Angular 在启动过程中自动为我们创建一个应用级注入器。

src/main.ts (bootstrap)

platformBrowserDynamic().bootstrapModule(AppModule);

We do have to configure the injector by registering the providers that create the services our application requires. We'll explain what providers are later in this chapter.

我们必须通过注册提供商 (provider) 来配置注入器,这些提供商为应用创建所需服务。 在本章的稍后部分会解释什么是提供商

We can either register a provider within an NgModule or in application components

或者在 NgModule 中注册提供商,或者在应用组件中。

Registering providers in an NgModule

在 NgModule 中注册提供商

Here's our AppModule where we register a Logger, a UserService, and an APP_CONFIG provider.

下面的例子是在 AppModule 中注册LoggerUserServiceAPP_CONFIG提供商。

src/app/app.module.ts (excerpt)

@NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, CarComponent, HeroesComponent, /* . . . */ ], providers: [ UserService, { provide: APP_CONFIG, useValue: HERO_DI_CONFIG } ], bootstrap: [ AppComponent ] }) export class AppModule { }

Registering providers in a component

在组件中注册提供商

Here's a revised HeroesComponent that registers the HeroService.

下面是更新的HerosComponent,它注册了HeroService

src/app/heroes/heroes.component.ts

import { Component } from '@angular/core'; import { HeroService } from './hero.service'; @Component({ selector: 'my-heroes', providers: [HeroService], template: ` <h2>Heroes</h2> <hero-list></hero-list> ` }) export class HeroesComponent { }

When to use the NgModule and when an application component?

该用 NgModule 还是应用组件?

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.

一方面,NgModule 中的提供商是被注册到根注入器。这意味着在 NgModule 中注册的提供商可以被整个应用访问。

On the other hand, a provider registered in an application component is available only on that component and all its children.

另一方面,在应用组件中注册的提供商只在该组件及其子组件中可用。

We want the APP_CONFIG service to be available all across the application, but a HeroService is only used within the Heroes feature area and nowhere else.

我们希望APP_CONFIG服务在整个应用中可用,而HeroService只需在英雄特性区可用,在其它地方都不可用。

Also see "Should I add app-wide providers to the root AppModule or the root AppComponent?" in the NgModule FAQ .

参见 NgModule FAQ 一章的 我该把“全应用级”提供商加到根模块AppModule还是根组件AppComponent

Preparing the HeroListComponent for injection

为注入准备HeroListComponent

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 we explained earlier. It's a small change:

HeroListComponent应该从注入的HeroService获取英雄数据。 遵照依赖注入模式的要求,组件必须在它的构造函数中请求这些服务,就像以前解释过的那样。 只是个小改动:

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> ` }) export class HeroListComponent { 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> ` }) export class HeroListComponent { heroes = HEROES; }

Focus on the constructor

来看看构造函数

Adding a parameter to the constructor isn't all that's happening here.

往构造函数中添加参数并不是这里所发生的一切。

constructor(heroService: HeroService) { this.heroes = heroService.getHeroes(); }

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.

注意,构造函数参数的类型是HeroService,并且HeroListComponent类有一个@Component装饰器 (往上翻可以确认)。另外,记得父级组件 (HeroesComponent) 有HeroServiceproviders信息。

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.

构造函数参数类型、@Component装饰器和父级的providers信息合起来告诉 Angular 的注入器, 任何新建HeroListComponent的时候,注入一个HeroService的实例。

Implicit injector creation

显性注入器的创建

When we introduced the idea of an injector above, we showed how to use it to create a new Car. Here we also show how such an injector would be explicitly created:

在前面介绍注入器时,展示了如何使用它创建一个新Car。这里,也展示一下如何显性的创建这样的注入器:

injector = ReflectiveInjector.resolveAndCreate([Car, Engine, Tires]); let car = injector.get(Car);

We won't find code like that in the Tour of Heroes or any of our other samples. We could write code that explicitly creates an injector if we had to, but 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. If we let Angular do its job, we'll enjoy the benefits of automated dependency injection.

无论在《英雄指南》还是其它范例中,都没有出现这样的代码。 在必要时,可以使用显式注入器的代码,但却很少这样做。 当 Angular 创建组件时 —— 无论通过像<hero-list></hero-list>这样的 HTML 标签还是通过路由导航到组件 —— 它都会自己管理好注入器的创建和调用。 只要让 Angular 做好它自己的工作,我们就能安心享受“自动依赖注入”带来的好处。

Singleton services

单例服务

Dependencies are singletons within the scope of an injector. In our example, a single HeroService instance is shared among the HeroesComponent and its HeroListComponent children.

在一个注入器的范围内,依赖都是单例的。 在这个例子中,HeroesComponent和它的子组件HeroListComponent共享同一个HeroService实例。

However, Angular DI is an hierarchical injection system, which means that nested injectors can create their own service instances. Learn more about that in the Hierarchical Injectors chapter.

然而,Angular DI 是一个分层的依赖注入系统,这意味着嵌套的注入器可以创建它们自己的服务实例。 要了解更多知识,参见多级依赖注入器一章。

Testing the component

测试组件

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:

例如,新建的HeroListComponent实例使用一个模拟 (mock) 服务,以便可以在测试中操纵它:

let expectedHeroes = [{name: 'A'}, {name: 'B'}] let mockService = <HeroService> {getHeroes: () => expectedHeroes } it('should have heroes when HeroListComponent created', () => { let hlc = new HeroListComponent(mockService); expect(hlc.heroes.length).toEqual(expectedHeroes.length); });

Learn more in Testing.

要学习更多知识,参见测试

When the service needs a service

当服务需要别的服务时

Our HeroService is very simple. It doesn't have any dependencies of its own.

这个HeroService非常简单。它本身不需要任何依赖。

What if it had a dependency? What if it reported its activities through a logging service? We'd apply the same constructor injection pattern, adding a constructor that takes a Logger parameter.

如果它也有依赖,该怎么办呢?例如,它需要通过日志服务来汇报自己的活动。 我们同样用构造函数注入模式,来添加一个带有Logger参数的构造函数。

Here is the revision compared to the original.

下面是在原来的基础上所做的修改:

import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; import { Logger } from '../logger.service'; @Injectable() export class HeroService { constructor(private logger: Logger) { } getHeroes() { this.logger.log('Getting heroes ...'); return HEROES; } } import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; @Injectable() export class HeroService { getHeroes() { return HEROES; } }

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.

现在,这个构造函数要求注入一个Logger类的实例,并把它存到名为logger的私有属性中。 当别人请求英雄数据时,在getHeroes方法中调用这个属性的方法。

Why @Injectable()?

为什么要用 @Injectable()?

@Injectable() marks a class as available to an injector for instantiation. Generally speaking, an injector will report an error when trying to instantiate a class that is not marked as @Injectable().

@Injectable() 标识一个类可以被注入器实例化。 通常,在试图实例化没有被标识为@Injectable()的类时,注入器会报错。

As it happens, we could have omitted @Injectable() from our first version of HeroService because it had no injected parameters. But we must have it now that our service has an injected dependency. We need it because Angular requires constructor parameter metadata in order to inject a Logger.

碰巧,第一版的HeroService省略了@Injectable(),那因为它没有注入的参数。 但是现在必须要有它,因为服务有了一个注入的依赖。 我们需要它,因为 Angular 需要构造函数参数的元数据来注入一个Logger

Suggestion: add @Injectable() to every service class
建议:为每个服务类都添加 @Injectable()

We recommend adding @Injectable() to every service class, even those that don't have dependencies and, therefore, do not technically require it. Here's why:

建议为每个服务类都添加@Injectable(),包括那些没有依赖严格来说并不需要它的。因为:

Injectors are also responsible for instantiating components like HeroesComponent. Why haven't we marked HeroesComponent as @Injectable()?

注入器同时负责实例化像HerosComponent这样的组件。为什么不标记HerosComponent@Injectable()呢?

We can add it if we really want to. It isn't necessary because the HeroesComponent is already marked with @Component, and this decorator class (like @Directive and @Pipe, which we'll 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.

我们可以添加它。但是没有必要,因为HerosComponent已经有@Component装饰器了, @Component(和随后将会学到的@Directive@Pipe一样)是 Injectable 的子类型。 实际上,正是这些Injectable装饰器是把一个类标识为注入器实例化的目标。

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.

在运行时,注入器可以从编译后的 JavaScript 代码中读取类的元数据, 并使用构造函数的参数类型信息来决定注入什么。

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.

不是每一个 JavaScript 类都有元数据。 TypeScript 编译器默认忽略元数据。 如果emitDecoratorMetadata编译器选项为true(在tsconfig.json中它应该为true), 编译器就会在生成的 JavaScript 中,为每一个至少拥有一个装饰器的类添加元数据。

While any decorator will trigger this effect, mark the service class with the Injectable decorator to make the intent clear.

当然,任何装饰器都会触发这个效果,用 Injectable 来标识服务 只是让这一意图更明显。

Always include the parentheses
总要带着括号

Always write @Injectable(), not just @Injectable. Our application will fail mysteriously if we forget the parentheses.

总是使用@Injectable()的形式,不能只用@Injectable。 如果忘了括号,应用就会神不知鬼不觉的失败!

Creating and registering a logger service

创建和注册日志服务

We're injecting a logger into our HeroService in two steps:

要把日志服务注入到HeroService中需要两步:

  1. Create the logger service.

    创建日志服务。

  2. Register it with the application.

    把它注册到应用中。

Our logger service is quite simple:

这个日志服务很简单:

src/app/logger.service.ts

import { Injectable } from '@angular/core'; @Injectable() export class Logger { logs: string[] = []; // capture logs for testing log(message: string) { this.logs.push(message); console.log(message); } }

We're likely to need the same logger service everywhere in our application, so we put it in the project's app folder, and we register it in the providers array of our application module, AppModule.

应用的每个角落都可能需要日志服务,所以把它放到项目的app目录, 并在应用模块AppModule的元数据providers数组里注册它。

src/app/app.module.ts (excerpt)

providers: [Logger]

If we forget to register the logger, Angular throws an exception when it first looks for the logger:

如果忘了注册这个日志服务,Angular 会在首次查找这个日志服务时,抛出一个异常。

EXCEPTION: No provider for Logger! (HeroListComponent -> HeroService -> Logger) (异常:Logger类没有提供商!(HeroListComponent -> HeroService -> Logger))

That's Angular telling us 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.

Angular 告诉我们,依赖注入器找不到日志服务的提供商。 在创建HeroListComponent的新实例时需要创建并注入HeroService, 而HeroService需要创建并注入一个Logger实例, Angular 需要这个Logger实例的提供商来。

The chain of creations started with the Logger provider. Providers are the subject of our next section.

这个“创建链”始于Logger的提供商。这个提供商就是下一节的主题。

Injector providers

注入器的提供商们

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.

提供商提供依赖值的一个具体的、运行时的版本。 注入器依靠提供商创建服务的实例,注入器再将服务的实例注入组件或其它服务。

We must register a service provider with the injector, or it won't know how to create the service.

必须为注入器注册一个服务的提供商,否则它不知道该如何创建该服务。

Earlier we registered the Logger service in the providers array of the metadata for the AppModule like this:

我们在前面通过AppModule元数据中的providers数组注册过Logger服务,就像这样:

providers: [Logger]

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.

有很多方式可以提供一些表现和行为像 Logger类的东西。 Logger类本身是一个显而易见而且自然而然的提供商。 但它不是唯一的选项。

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.

可以用其它备选提供商来配置注入器,只要它们能交付一个对象,其行为像Logger就可以了。 可以提供一个替代类。也就是可以提供一个像logger的对象。 可以给它一个提供商,让它调用可以创建日志服务的工厂函数。 所有这些方法,只要用在正确的场合,都可能是一个好的选择。

What matters is that the injector has a provider to go to when it needs a Logger.

最重要的是,当注入器需要一个Logger时,它得先有一个提供商。

The Provider class and provide object literal

Provider类和 provide 对象常量

We wrote the providers array like this:

像下面一样写providers数组:

providers: [Logger]

This is actually a shorthand expression for a provider registration using a provider object literal with two properties:

这其实是用于注册提供商的简写表达式。 使用的是一个带有两个属性的提供商对象字面量:

[{ provide: Logger, useClass: Logger }]

The first is the token that serves as the key for both locating a dependency value and registering the provider.

第一个是令牌 (token),它作为键值 (key) 使用,用于定位依赖值和注册提供商。

The second is a provider definition object, which we can think of as a recipe for creating the dependency value. There are many ways to create dependency values ... and many ways to write a recipe.

第二个是供应商定义对象。 可以把它看做是指导如何创建依赖值的配方。 有很多方式创建依赖值…… 也有很多方式可以写配方。

Alternative class providers

备选的类提供商

Occasionally we'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.

某些时候,我们会请求一个不同的类来提供服务。 下列代码告诉注入器,当有人请求Logger时,返回BetterLogger

[{ provide: Logger, useClass: BetterLogger }]

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.

假设EvenBetterLogger可以在日志消息中显示用户名。 这个日志服务从注入的UserService中取得用户, UserService通常也会在应用级注入。

@Injectable() class EvenBetterLogger extends Logger { constructor(private userService: UserService) { super(); } log(message: string) { let name = this.userService.user.name; super.log(`Message to ${name}: ${message}`); } }

Configure it like we did BetterLogger.

就像之前在BetterLogger中那样配置它。

[ UserService, { provide: Logger, useClass: EvenBetterLogger }]

Aliased class providers

别名类提供商

Suppose an old component 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.

假设某个旧组件依赖一个OldLogger类。 OldLoggerNewLogger具有相同的接口,但是由于某些原因, 我们不能升级这个旧组件并使用它。

When the old component logs a message with OldLogger, we want the singleton instance of NewLogger to handle it instead.

组件想使用OldLogger记录消息时,我们希望改用NewLogger的单例对象来记录。

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.

不管组件请求的是新的还是旧的日志服务,依赖注入器注入的都应该是同一个单例对象。 也就是说,OldLogger应该是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.

我们当然不会希望应用中有两个不同的NewLogger实例。 不幸的是,如果尝试通过useClass来把OldLogger作为NewLogger的别名,就会导致这样的后果。

[ NewLogger, // Not aliased! Creates two instances of `NewLogger` { provide: OldLogger, useClass: NewLogger}]

The solution: alias with the useExisting option.

解决方案:使用useExisting选项指定别名。

[ 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 service let silentLogger = { logs: ['Silent logger says "Shhhhh!". Provided via "useValue"'], log: () => {} };

Then we register a provider with the useValue option, which makes this object play the logger role.

于是可以通过useValue选项来注册提供商,它会让这个对象直接扮演 logger 的角色。

[{ provide: Logger, useValue: silentLogger }]

See more useValue examples in the Non-class dependencies and OpaqueToken sections.

查看更多useValue的例子,见非类依赖OpaqueToken

Factory providers

工厂提供商

Sometimes we need to create the dependent value dynamically, based on information we 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.

还假设这个可注入的服务没法通过独立的源访问此信息。

This situation calls for a factory provider.

这种情况下,请呼叫工厂提供商

Let's illustrate by adding a new business requirement: the HeroService must hide secret heroes from normal users. Only authorized users should see secret heroes.

下面通过添加新的业务需求来说明这一点: HeroService 必须对普通用户隐藏掉秘密英雄。 只有授权用户才能看到秘密英雄。

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.

就像EvenBetterLogger那样,HeroService需要了解此用户的身份。 它需要知道,这个用户是否有权看到隐藏英雄。 这个授权可能在单一的应用会话中被改变,例如,改用另一个用户的身份登录时。

Unlike EvenBetterLogger, we 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.

EvenBetterLogger不同,不能把UserService注入到HeroService中。 HeroService无权访问用户信息,来决定谁有授权谁没有授权。

Why? We don't know either. Stuff like this happens.

为什么?我们也不知道。这样的事经常发生。

Instead the HeroService constructor takes a boolean flag to control display of secret heroes.

HeroService的构造函数带上一个布尔型的标志,来控制是否显示隐藏的英雄。

src/app/heroes/hero.service.ts (excerpt)

constructor( private logger: Logger, private isAuthorized: boolean) { } getHeroes() { let auth = this.isAuthorized ? 'authorized ' : 'unauthorized'; this.logger.log(`Getting heroes for ${auth} user.`); return HEROES.filter(hero => this.isAuthorized || !hero.isSecret); }

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.

我们可以注入Logger,但是不能注入逻辑型的isAuthorized。 我们不得不通过通过工厂提供商创建这个HeroService的新实例。

A factory provider needs a factory function:

工厂提供商需要一个工厂方法:

src/app/heroes/hero.service.provider.ts (excerpt)

let heroServiceFactory = (logger: Logger, userService: UserService) => { return new HeroService(logger, userService.user.isAuthorized); };

Although the HeroService has no access to the UserService, our factory function does.

虽然HeroService不能访问UserService,但是工厂方法可以。

We inject both the Logger and the UserService into the factory provider and let the injector pass them along to the factory function:

同时把LoggerUserService注入到工厂提供商中,并且让注入器把它们传给工厂方法:

src/app/heroes/hero.service.provider.ts (excerpt)

export let heroServiceProvider = { provide: HeroService, useFactory: heroServiceFactory, deps: [Logger, UserService] };

The useFactory field tells Angular that the provider is a factory function whose implementation is the heroServiceFactory.

useFactory字段告诉 Angular:这个提供商是一个工厂方法,它的实现是heroServiceFactory

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.

deps属性是提供商令牌数组。 LoggerUserService类作为它们自身类提供商的令牌。 注入器解析这些令牌,把相应的服务注入到工厂函数中相应的参数中去。

Notice that we captured the factory provider in an exported variable, heroServiceProvider. This extra step makes the factory provider reusable. We can register our HeroService with this variable wherever we need it.

注意,我们在一个导出的变量中捕获了这个工厂提供商:heroServiceProvider。 这个额外的步骤让工厂提供商可被复用。 无论哪里需要,都可以使用这个变量注册HeroService

In our sample, we need it only in the HeroesComponent, where it replaces the previous HeroService registration in the metadata providers array. Here we see the new and the old implementation side-by-side:

在这个例子中,只在HeroesComponent中需要它, 这里,它代替了元数据providers数组中原来的HeroService注册。 对比一下新的和旧的实现:

import { Component } from '@angular/core'; import { heroServiceProvider } from './hero.service.provider'; @Component({ selector: 'my-heroes', template: ` <h2>Heroes</h2> <hero-list></hero-list> `, providers: [heroServiceProvider] }) export class HeroesComponent { } import { Component } from '@angular/core'; import { HeroService } from './hero.service'; @Component({ selector: 'my-heroes', providers: [HeroService], template: ` <h2>Heroes</h2> <hero-list></hero-list> ` }) export class HeroesComponent { }

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. The token is the key to the map.

当向注入器注册提供商时,实际上是把这个提供商和一个 DI 令牌关联起来了。 注入器维护一个内部的令牌-提供商映射表,这个映射表会在请求依赖时被引用到。 令牌就是这个映射表中的键值。

In all previous examples, the dependency value has been a class instance, and the class type served as its own lookup key. Here we get a HeroService directly from the injector by supplying the HeroService type as the token:

在前面的所有例子中,依赖值都是一个类实例,并且类的类型作为它自己的查找键值。 在下面的代码中,HeroService类型作为令牌,直接从注入器中获取HeroService 实例:

heroService: HeroService = this.injector.get(HeroService);

We have similar good fortune 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:

编写需要基于类的依赖注入的构造函数对我们来说是很幸运的。 只要定义一个HeroService类型的构造函数参数, Angular 就会知道把跟HeroService类令牌关联的服务注入进来:

constructor(heroService: HeroService)

This is 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, 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:

应用程序经常为很多很小的因素定义配置对象(例如应用程序的标题或网络API终点的地址)。 but these configuration objects aren't always instances of a class. They can be object literals

src/app/app-config.ts (excerpt)

export interface AppConfig { apiEndpoint: string; title: string; } export const HERO_DI_CONFIG: AppConfig = { apiEndpoint: 'api.heroes.com', title: 'Dependency Injection' };

We'd like to make this configuration object available for injection. We know we can register an object with a value provider.

我们想让这个配置对象在注入时可用,而且知道可以使用值提供商来注册一个对象。

But what should we use as the token? We don't have a class to serve as a token. There is no AppConfig class.

但是,这种情况下用什么作令牌呢? 我们没办法找一个类来当作令牌,因为没有Config类。

TypeScript interfaces aren't valid tokens

TypeScript 接口不是一个有效的令牌

The HERO_DI_CONFIG constant has an interface, AppConfig. Unfortunately, we cannot use a TypeScript interface as a token:

CONFIG常量有一个接口:AppConfig。不幸的是,不能把 TypeScript 接口用作令牌:

// FAIL! Can't use interface as provider token [{ provide: AppConfig, useValue: HERO_DI_CONFIG })]
// FAIL! Can't inject using the interface as the parameter type constructor(private config: AppConfig){ }

That seems strange if we're used to dependency injection in strongly typed languages, where an interface is the preferred dependency lookup key.

对于习惯于在强类型的语言中使用依赖注入的开发人员,这会看起来很奇怪, 因为在强类型语言中,接口是首选的用于查找依赖的主键。

It's not Angular's fault. 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.

这不是 Angular 的错。接口只是 TypeScript 设计时 (design-time) 的概念。JavaScript 没有接口。 TypeScript 接口不会出现在生成的 JavaScript 代码中。 在运行期,没有接口类型信息可供 Angular 查找。

OpaqueToken

One solution to choosing a provider token for non-class dependencies is to define and use an OpaqueToken. The definition looks like this:

解决方案是定义和使用 OpaqueToken(不透明的令牌)。定义方式类似于这样:

import { OpaqueToken } from '@angular/core'; export let APP_CONFIG = new OpaqueToken('app.config');

We register the dependency provider using the OpaqueToken object:

使用这个OpaqueToken对象注册依赖的提供商:

providers: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }]

Now we can inject the configuration object into any constructor that needs it, with the help of an @Inject decorator:

现在,在@Inject装饰器的帮助下,这个配置对象可以注入到任何需要它的构造函数中:

constructor(@Inject(APP_CONFIG) config: AppConfig) { this.title = config.title; }

Although the AppConfig interface plays no role in dependency injection, it supports typing of the configuration object within the class.

虽然ConfigAppConfig接口在依赖注入过程中没有任何作用,但它为该类中的配置对象提供了强类型信息。

Or we can provide and inject the configuration object in an ngModule like AppModule.

或者在 ngModule 中提供并注入这个配置对象,如AppModule

src/app/app.module.ts (ngmodule-providers)

providers: [ UserService, { provide: APP_CONFIG, useValue: HERO_DI_CONFIG } ],

Optional dependencies

可选依赖

Our HeroService requires a Logger, but what if it could get by without a logger? We can tell Angular that the dependency is optional by annotating the constructor argument with @Optional():

HeroService需要一个Logger,但是如果想不提供 Logger 也能得到它,该怎么办呢? 可以把构造函数的参数标记为@Optional(),告诉 Angular 该依赖是可选的:

import { Optional } from '@angular/core';
constructor(@Optional() private logger: Logger) { if (this.logger) { this.logger.log(some_message); } }

When using @Optional(), our code must be prepared for a null value. If we don't register a logger somewhere up the line, the injector will set the value of logger to null.

当使用@Optional()时,代码必须准备好如何处理空值。 如果其它的代码没有注册一个 logger,注入器会设置该logger的值为空 null。

Summary

总结

We learned the basics of Angular dependency injection in this chapter. We can register various kinds of providers, and we know how to ask for an injected object (such as a service) by adding a parameter to a constructor.

本章,我们学习了 Angular 依赖注入的基础知识。 我们可以注册很多种类的提供商,知道如何通过添加构造函数的参数来请求一个注入对象(例如一个服务)。

Angular dependency injection is more capable than we've described. We can learn more about its advanced features, beginning with its support for nested injectors, in the Hierarchical Dependency Injection chapter.

Angular 依赖注入比前面描述的更能干。 学习更多高级特性,如对嵌套注入器的支持,见多级依赖注入一章。

Appendix: Working with injectors directly

附录:直接使用注入器

We rarely work directly with an injector, but here's an InjectorComponent that does.

这里的InjectorComponent直接使用了注入器, 但我们很少直接使用它。

src/app/injector.component.ts

@Component({ selector: 'my-injectors', template: ` <h2>Other Injections</h2> <div id="car">{{car.drive()}}</div> <div id="hero">{{hero.name}}</div> <div id="rodent">{{rodent}}</div> `, providers: [Car, Engine, Tires, heroServiceProvider, Logger] }) export class InjectorComponent { car: Car = this.injector.get(Car); heroService: HeroService = this.injector.get(HeroService); hero: Hero = this.heroService.getHeroes()[0]; constructor(private injector: Injector) { } get rodent() { let rousDontExist = `R.O.U.S.'s? I don't think they exist!`; return this.injector.get(ROUS, rousDontExist); } }

An Injector is itself an injectable service.

Injector本身是可注入的服务。

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.

在这个例子中,Angular 把组件自身的Injector注入到了组件的构造函数中。 然后,组件向注入的注入器请求它所需的服务。

Note that the services themselves are not injected into the component. They are retrieved by calling injector.get.

注意,这些服务本身没有注入到组件,它们是通过调用injector.get获得的。

The get method throws an error if it can't resolve the requested service. We can call get with a second parameter (the value to return if the service is not found) instead, which we do in one case to retrieve a service (ROUS) that isn't registered with this or any ancestor injector.

get方法如果不能解析所请求的服务,会抛出异常。 调用get时,还可以使用第二个参数,一旦获取的服务 (ROUS) 没有在当前或任何祖先注入器中注册过, 就把它作为返回值。

The technique we just described is an example of the 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 to discover what it does.

避免使用此技术,除非确实需要它。 它会鼓励鲁莽的方式,就像在这里看到的。 它难以解释、理解和测试。 仅通过阅读构造函数,没法知道这个类需要什么或者它将做什么。 它可以从任何祖先组件中获得服务,而不仅仅是它自己。 会迫使我们深入它的实现,才可能明白它都做了啥。

Framework developers may take this approach when they must acquire services generically and dynamically.

框架开发人员必须采用通用的或者动态的方式获取服务时,可能采用这个方法。

Appendix: Why we recommend 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 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, we'll get a runtime null reference error.

如果我们蔑视这个建议,并且 —— 比如说 —— 把HeroServiceHeroesComponent组合在同一个文件里, 就得把组件定义放在最后面! 如果把组件定义在了服务的前面, 在运行时抛出空指针错误。

We 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.

forwardRef()方法的帮助下,实际上也可以先定义组件, 具体说明见这个博客。 但是为什么要先给自己找麻烦呢? 还是通过在独立的文件中定义组件和服务,完全避免此问题吧。

下一步

模板语法