0
0
AngularConceptBeginner · 3 min read

What is Dependency Injection in Angular: Simple Explanation and Example

Dependency injection in Angular is a design pattern where Angular automatically provides components with the services or objects they need, called dependencies. Instead of creating dependencies inside components, Angular injects them, making code easier to manage and test.
⚙️

How It Works

Imagine you need a coffee machine to make coffee, but instead of buying and maintaining it yourself, a coffee shop provides it for you whenever you need. Dependency injection in Angular works similarly: components ask for what they need, and Angular provides it automatically.

Angular has a special system called the injector that keeps track of all the services and objects your app needs. When a component or service asks for a dependency, the injector finds or creates it and hands it over. This way, components don’t have to know how to create or manage their dependencies, making the code cleaner and easier to change.

💻

Example

This example shows a simple Angular service injected into a component. The service provides a greeting message, and the component uses it without creating the service itself.

typescript
import { Injectable, Component } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class GreetingService {
  getGreeting() {
    return 'Hello from the GreetingService!';
  }
}

@Component({
  selector: 'app-root',
  template: `<h1>{{ greeting }}</h1>`
})
export class AppComponent {
  greeting: string;

  constructor(private greetingService: GreetingService) {
    this.greeting = this.greetingService.getGreeting();
  }
}
Output
<h1>Hello from the GreetingService!</h1>
🎯

When to Use

Use dependency injection in Angular whenever your components or services need to use shared functionality like data fetching, logging, or configuration. It helps keep your code organized and testable by separating how things are created from how they are used.

For example, if multiple components need to get user data from a server, you create one user service and inject it wherever needed. This avoids repeating code and makes updates easier.

Key Points

  • Dependency injection lets Angular provide needed services automatically.
  • It improves code organization by separating creation from usage.
  • Angular’s injector manages service lifetimes and sharing.
  • It makes testing easier by allowing mock dependencies.

Key Takeaways

Dependency injection lets Angular supply components with needed services automatically.
It keeps code clean by separating how dependencies are created from how they are used.
Angular’s injector manages and shares dependencies efficiently.
Use it to share common services like data access or logging across your app.
It makes your app easier to test and maintain.