DEV Community

Anjali Gurjar
Anjali Gurjar

Posted on

What is Dependency Injection (DI)

DI is a design pattern that helps inject dependencies (services, objects) into components instead of manually creating them.
Prevents tight coupling and improves reusability.

How DI Works in Angular?
Provide the Service (in @Injectable).
Inject into Constructor (in a component or another service).
Use the Service.

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root' // Provides globally
})
export class LoggerService {
log(message: string) {
console.log("Log:", message);
}
}

import { Component } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({
selector: 'app-home',
template: <button (click)="logMessage()">Log</button>
})
export class HomeComponent {
constructor(private logger: LoggerService) {}

logMessage() {
this.logger.log('Hello from HomeComponent!');
}
}

Different Injection Scenarios
1️⃣ ProvidedIn: 'root' vs 'any' vs Module Level
Option Scope Usage
providedIn: 'root' Available in entire app Default
providedIn: 'any' Available in lazy-loaded modules Useful for optimizing memory
Module Level Available in specific module only providers: [MyService] in @NgModule

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more