Skip to main content
Angular Dependency Injection

Module Overview

Estimated Time: 3-4 hours | Difficulty: Intermediate | Prerequisites: Module 3
Dependency Injection (DI) is a design pattern where objects receive their dependencies from external sources rather than creating them. Angular has a powerful DI system built-in that makes your code more testable, maintainable, and modular. What You’ll Learn:
  • Creating injectable services
  • Understanding the injector hierarchy
  • Provider configurations
  • The modern inject() function
  • InjectionTokens for configuration
  • Multi-providers and use cases

What is Dependency Injection?


Creating a Service

Basic Service

Using the Service


inject() vs Constructor Injection

Angular provides two ways to inject dependencies:

Modern: inject() Function

Classic: Constructor Injection

Recommendation: Use inject() for new code. It’s more concise, works with functional features like guards and resolvers, and doesn’t require decorator metadata for TypeScript.

Injector Hierarchy

Angular has a hierarchical injector system:

providedIn Options


Provider Configurations

Providing in Component

useClass - Alternative Implementation

useValue - Static Values

useFactory - Dynamic Creation

useExisting - Alias


InjectionToken

For non-class dependencies, use InjectionToken:

Multi-Providers

Provide multiple values for the same token:

Service Design Patterns

State Service with Signals

Repository Pattern

Facade Pattern


Testing Services


Practice Exercise

Exercise: Build a Shopping Cart Service

Create a CartService that:
  1. Uses signals for reactive state
  2. Supports add, remove, update quantity
  3. Computes total price and item count
  4. Persists to localStorage

Summary

1

Services

Use @Injectable to create reusable, testable services
2

inject() Function

Modern way to inject dependencies, works everywhere
3

Injector Hierarchy

Services can be scoped to root, module, or component level
4

Providers

Configure with useClass, useValue, useFactory, or useExisting
5

InjectionTokens

Use for non-class dependencies and configuration

Next Steps

Next: Angular Signals

Deep dive into Angular’s reactive primitive for modern state management