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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay