Angular's DI

The last example introduced a hypothetical Injector object. Angularsimplifies DI even further. With Angular, programmers almost never have to getbogged down with injection details.

Angular's DI system is (mostly) controlled through @NgModule. Specificallythe providers and declarations array. (declarations is where we put components,pipes and directives; providers is where we put services)

For example:

  1. import { Injectable, NgModule } from '@angular/core';
  2. @Component({
  3. // ...
  4. })
  5. class ChatWidget {
  6. constructor(private authService: AuthService, private authWidget: AuthWidget,
  7. private chatSocket: ChatSocket) {}
  8. }
  9. @NgModule({
  10. declarations: [ ChatWidget ]
  11. })
  12. export class AppModule {
  13. };

In the above example the AppModule is told about the ChatWidget class. Another wayof saying this is that Angular has been provided a ChatWidget.

That seems pretty straightforward, but astute readers will be wondering howAngular knows how to build ChatWidget. What if ChatWidget was a string, ora plain function?

Angular assumes that it's being given a class.

What about AuthService, AuthWidget and ChatSocket? How is ChatWidget getting those?

It's not, at least not yet. Angular does not know about them yet. That canbe changed easily enough:

  1. import { Injectable, NgModule } from '@angular/core';
  2. @Component({
  3. // ...
  4. })
  5. class ChatWidget {
  6. constructor(private authService: AuthService, private authWidget: AuthWidget,
  7. private chatSocket: ChatSocket) {}
  8. }
  9. @Component({
  10. // ...
  11. })
  12. class AuthWidget {}
  13. @Injectable()
  14. class AuthService {}
  15. @Injectable()
  16. class ChatSocket {}
  17. @NgModule({
  18. declarations[ ChatWidget, AuthWidget ]
  19. providers: [ AuthService, ChatSocket ],
  20. })

Okay, this is starting to look a little bit more complete. Although it's stillunclear how ChatWidget is being told about its dependencies. Perhaps that isrelated to those odd @Injectable statements.

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