What is dependency injection in Angular, and how does a component receive a service?
Short answer
Dependency injection means a component or another service does not create its own dependencies directly, but instead receives them automatically, usually through its constructor, from Angular's injection system, which handles creating and providing the correct shared instance.
Advertisement
AModel answer
Dependency injection means a component or another service does not create its own dependencies directly, but instead receives them automatically, usually through its constructor, from Angular's injection system, which handles creating and providing the correct shared instance.
@Component({ selector: 'app-user-list' })
export class UserListComponent {
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUsers().subscribe((users) => this.users = users);
}
}Real-world example
A user list component simply asks for a UserService in its constructor, and Angular automatically provides the correct shared instance, without the component needing to know anything about how that service was actually created.
Likely follow-ups
- What happens if Angular cannot find a provider for a requested dependency?
- How does dependency injection make it easier to test a component in isolation?
Related topics