Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Angular FAQ: Top Questions

11. What is Dependency Injection in Angular?

Dependency Injection (DI) is a design pattern and core feature in Angular that implements Inversion of Control (IoC). Rather than creating dependencies (like services) manually within a class, DI allows Angular to instantiate and supply those dependencies from an external source. This enables greater flexibility, modularity, and testability across applications.

Angular’s DI system automatically resolves and injects the required services into components, pipes, directives, or other services via constructor injection.

  • Modularity & Decoupling:
    • DI promotes a loosely coupled architecture, making each unit (component, service, etc.) easier to manage and test independently.
  • Provider Configuration:
    • Services must be declared in the providers array or using the @Injectable({ providedIn: 'root' }) shorthand to be available for injection.
    • Scopes include:
      • root – singleton across the application
      • feature modules – scoped to specific modules
      • component-level – unique instances per component
  • Constructor Injection:
    • Angular uses the class constructor to inject dependencies at runtime.
    • The injected services can then be used throughout the class logic.
  • Testability:
    • DI makes it easy to mock dependencies in unit tests, leading to better isolation and control over test scenarios.

// api.service.ts

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

@Injectable({ providedIn: 'root' })
export class ApiService {
  getData() {
    return ['Angular', 'React', 'Vue'];
  }
}
        

// app.component.ts

import { Component } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  template: '<ul><li *ngFor="let tech of technologies">{{ tech }}</li></ul>'
})
export class AppComponent {
  technologies: string[] = [];

  constructor(private apiService: ApiService) {
    this.technologies = this.apiService.getData();
  }
}
        

Explanation of the Example Code:

  • ApiService is annotated with @Injectable({ providedIn: 'root' }), making it a singleton available across the application without needing to declare it in a providers array manually.
  • In AppComponent, the ApiService is injected via the constructor using the private apiService parameter.
  • The service's getData() method is used to populate the technologies array, which is rendered in the template with *ngFor.

Angular’s DI system simplifies the management of service dependencies and helps maintain clean, testable, and maintainable code across both small and large applications.