Angular's DI
The last example introduced a hypothetical Injector object. Angular simplifies DI even further. With Angular, programmers almost never have to get bogged down with injection details.
Angular's DI system is (mostly) controlled through @NgModule. Specifically the 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
3
@Component({
4
// ...
5
})
6
class ChatWidget {
7
constructor(private authService: AuthService, private authWidget: AuthWidget,
8
private chatSocket: ChatSocket) {}
9
}
10
11
@NgModule({
12
declarations: [ ChatWidget ]
13
})
14
export class AppModule {
15
};
Copied!
In the above example the AppModule is told about the ChatWidget class. Another way of saying this is that Angular has been provided a ChatWidget.
That seems pretty straightforward, but astute readers will be wondering how Angular knows how to build ChatWidget. What if ChatWidget was a string, or a 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 can be changed easily enough:
1
import { Injectable, NgModule } from '@angular/core';
2
3
@Component({
4
// ...
5
})
6
class ChatWidget {
7
constructor(private authService: AuthService, private authWidget: AuthWidget,
8
private chatSocket: ChatSocket) {}
9
}
10
11
@Component({
12
// ...
13
})
14
class AuthWidget {}
15
16
@Injectable()
17
class AuthService {}
18
19
@Injectable()
20
class ChatSocket {}
21
22
@NgModule({
23
declarations[ ChatWidget, AuthWidget ]
24
providers: [ AuthService, ChatSocket ],
25
})
Copied!
Okay, this is starting to look a little bit more complete. Although it's still unclear how ChatWidget is being told about its dependencies. Perhaps that is related to those odd @Injectable statements.
Copy link