The Injector Tree

Angular injectors (generally) return singletons. That is, in the previous example,all components in the application will receive the same randomnumber. In Angular 1.x there was only one injector, and all services weresingletons. Angular overcomes this limitation by using a tree of injectors.

In Angular there is not just one injector per application, there is at least one injector per application. Injectors are organized in a tree that parallels Angular's component tree.

Consider the following tree, which models a chat application consisting of twoopen chat windows, and a login/logout widget.

Image of a Component Tree, and a DI Tree

Figure: Image of a Component Tree, and a DI Tree

In the image above, there is one root injector, which is established through@NgModule's providers array. There's a LoginService registered with theroot injector.

Below the root injector is the root @Component. This particular component hasno providers array and will use the root injector for all of its dependencies.

There are also two child injectors, one for each ChatWindow component. Eachof these components has their own instantiation of a ChatService.

There is a third child component, Logout/Login, but it has no injector.

There are several grandchild components that have no injectors. There areChatFeed and ChatInput components for each ChatWindow. There are alsoLoginWidget and LogoutWidget components with Logout/Login as theirparent.

The injector tree does not make a new injector for every component,but does make a new injector for every component with a providers array in its decorator.Components that have no providers array look to their parent component for an injector.If the parent does not have an injector, it looks up until it reaches the root injector.

Warning: Be careful with provider arrays. If a child component is decorated with aproviders array that contains dependencies that were also requested in the parentcomponent(s), the dependencies the child receives will shadow the parent dependencies.This can have all sorts of unintended consequences.

Consider the following example:

app/module.ts

  1. import { NgModule } from '@angular/core';
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { AppComponent } from './app.component';
  4. import { ChildInheritorComponent, ChildOwnInjectorComponent } from './components/index';
  5. import { Unique } from './services/unique';
  6. const randomFactory = () => { return Math.random(); };
  7. @NgModule({
  8. imports: [BrowserModule],
  9. declarations: [
  10. AppComponent,
  11. ChildInheritorComponent,
  12. ChildOwnInjectorComponent,
  13. ],
  14. /** Provide dependencies here */
  15. providers: [Unique],
  16. bootstrap: [AppComponent],
  17. })
  18. export class AppModule {}

In the example above, Unique is bootstrapped into the root injector.

app/services/unique.ts

  1. import { Injectable } from '@angular/core';
  2. @Injectable()
  3. export class Unique {
  4. value = (+Date.now()).toString(16) + '.' +
  5. Math.floor(Math.random() * 500);
  6. }

The Unique service generates a value unique to its instance upon instantiation.

app/components/child-inheritor.component.ts

  1. import { Component, Inject } from '@angular/core';
  2. import { Unique } from '../services/unique';
  3. @Component({
  4. selector: 'app-child-inheritor',
  5. template: `<span>{{ value }}</span>`
  6. })
  7. export class ChildInheritorComponent {
  8. value = this.u.value;
  9. constructor(private u: Unique) { }
  10. }

The child inheritor has no injector. It will traverse the component tree upwards looking for an injector.

app/components/child-own-injector.component.ts

  1. import { Component, Inject } from '@angular/core';
  2. import { Unique } from '../services/unique';
  3. @Component({
  4. selector: 'child-own-injector',
  5. template: `<span>{{ value }}</span>`,
  6. providers: [Unique]
  7. })
  8. export class ChildOwnInjectorComponent {
  9. value = this.u.value;
  10. constructor(private u: Unique) { }
  11. }

The child own injector component has an injector that is populated with its owninstance of Unique. This component will not share the same value as theroot injector's Unique instance.

app/containers/app.ts

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <p>
  5. App's Unique dependency has a value of {{ value }}
  6. </p>
  7. <p>
  8. which should match
  9. </p>
  10. <p>
  11. ChildInheritor's value:
  12. <app-child-inheritor></app-child-inheritor>
  13. </p>
  14. <p>
  15. However,
  16. </p>
  17. <p>
  18. ChildOwnInjector should have its own value:
  19. <app-child-own-injector></app-child-own-injector>
  20. </p>
  21. <p>
  22. ChildOwnInjector's other instance should also have its own value:
  23. <app-child-own-injector></app-child-own-injector>
  24. </p>`,
  25. })
  26. export class AppComponent {
  27. value: number = this.u.value;
  28. constructor(private u: Unique) { }
  29. }

View Example

原文: https://angular-2-training-book.rangle.io/handout/di/angular2/the_injector_tree.html