Performance: How dependency injection works in Angular
Dependency injection affects initial load time and runtime responsiveness by managing service creation and reuse efficiently.
import { Injectable, Component } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { constructor() { } } @Component({ selector: 'app-example', template: '<p>Example</p>' }) export class ExampleComponent { constructor(private dataService: DataService) { } }
import { Injectable, Component } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { constructor() { } } @Component({ selector: 'app-example', template: '<p>Example</p>', providers: [DataService] }) export class ExampleComponent { constructor(private dataService: DataService) { } }
| Pattern | Service Instances | Memory Use | Initialization Time | Verdict |
|---|---|---|---|---|
| Service provided in component | Multiple per component | High | Longer due to repeated instantiation | [X] Bad |
| Service provided in root | Single shared instance | Low | Short due to reuse | [OK] Good |
@Injectable marks a class as available for dependency injection.@Component is for components, @NgModule for modules, and @Input for input properties, none make a class injectable.import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class LoggerService {
log(message: string) {
console.log('Log:', message);
}
}
import { Component } from '@angular/core';
import { LoggerService } from './logger.service';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(private logger: LoggerService) {
this.logger.log('Hello');
}
}LoggerService is injected into AppComponent via constructor and used to log a message.log method prints 'Log:' plus the message 'Hello', so console shows 'Log: Hello'.import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
getData() { return [1, 2, 3]; }
}
import { Component } from '@angular/core';
@Component({ selector: 'app-data', template: '' })
export class DataComponent {
constructor(private dataService: DataService) {}
}@Injectable() but no providedIn or provider registration, so Angular doesn't know where to provide it.DataService into DataComponent.@Injectable({ providedIn: 'root' }) on the class and inject twice in constructor injects the same instance twice, B duplicates classes unnecessarily, D is error-prone and not recommended.Pass the test and this pattern moves unknown