Back to results for “Dependency injection”
Angular › Services & Dependency Injection

What is dependency injection in Angular, and how does a component receive a service?

Beginner

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.

Common 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?