Lazy Loading and the Dependency Injection Tree

Lazy loaded modules create their own branch on the Dependency Injection (DI) tree. This means that it's possible to have services that belong to a lazy loaded module, that are not accessible by the root module or any other eagerly loaded module of our application.

To show this behaviour, let's continue with the example of the previous section and add a CounterService to our LazyModule.

app/lazy/lazy.module.ts

  1. ...
  2. import { CounterService } from './counter.service';
  3. @NgModule({
  4. ...
  5. providers: [CounterService]
  6. })
  7. export class LazyModule {}

Here we added the CounterService to the providers array. Our CounterService is a simple class that holds a reference to a counter property.

app/lazy/counter.service.ts

  1. import { Injectable } from '@angular/core';
  2. @Injectable()
  3. export class CounterService {
  4. counter = 0;
  5. }

We can modify the LazyComponent to use this service with a button to increment the counter property.

app/lazy/lazy.component.ts

  1. import { Component } from '@angular/core';
  2. import { CounterService } from './counter.service';
  3. @Component({
  4. template: `
  5. <p>Lazy Component</p>
  6. <button (click)="increaseCounter()">Increase Counter</button>
  7. <p>Counter: {{ counterService.counter }}</p>
  8. `
  9. })
  10. export class LazyComponent {
  11. constructor(public counterService: CounterService) {}
  12. increaseCounter() {
  13. this.counterService.counter += 1;
  14. }
  15. }

View Example

The service is working. If we increment the counter and then navigate back and forth between the eager and the lazy routes, the counter value will persist in the lazy loaded module.

But the question is, how can we verify that the service is isolated and cannot be used in a component that belongs to a different module? Let's try to use the same service in the EagerComponent.

app/eager.component.ts

  1. import { Component } from '@angular/core';
  2. import { CounterService } from './lazy/counter.service';
  3. @Component({
  4. template: `
  5. <p>Eager Component</p>
  6. <button (click)="increaseCounter()">Increase Counter</button>
  7. <p>Counter: {{ counterService.counter }}</p>
  8. `
  9. })
  10. export class EagerComponent {
  11. constructor(public counterService: CounterService) {}
  12. increaseCounter() {
  13. this.counterService.counter += 1;
  14. }
  15. }

If we try to run this new version of our code, we are going to get an error message in the browser console:

  1. No provider for CounterService!

What this error tells us is that the AppModule, where the EagerComponent is defined, has no knowledge of a service called CounterService. CounterService lives in a different branch of the DI tree created for LazyModule when it was lazy loaded in the browser.

原文: https://angular-2-training-book.rangle.io/handout/modules/lazy-load-di.html