Services & Dependency Injection: Sharing Logic
7 min read
Services & Dependency Injection: Sharing Logic 🛡️
Welcome to Section 4. Up to this point, we have constructed components that function largely in isolation. However, a robust application requires components to communicate, share data, and delegate complex business logic to specialized utility classes. In Angular, we achieve this through Services and the Dependency Injection (DI) system.
This guide will transition your understanding from isolated view-logic to interconnected application architecture.
1. The "Why": Understanding Dependency Injection (DI) 💉
Before writing code, we must understand the architectural problem that Dependency Injection solves.
The Definition
Dependency Injection (DI) is a design pattern in which a class requests dependencies from external sources rather than creating them itself.
The Problem: Tight Coupling
Without DI, if Component A needs a Calculator class to perform math, it instantiates it directly.
// ❌ BAD: Tight Coupling (Without DI)
class Calculator {
add(a: number, b: number) { return a + b; }
}
class ComponentA {
private calc: Calculator;
constructor() {
// ComponentA is responsible for creating Calculator.
// If Calculator's constructor changes, ComponentA breaks.
this.calc = new Calculator();
}
}This is Tight Coupling.
- Hard to maintain: If
Calculatorchanges its requirements, every component using it must be updated. - Hard to test: You cannot easily swap
Calculatorfor aMockCalculatorduring testing.
The Solution: Inversion of Control
With DI, Component A simply declares that it needs a calculator. The Angular framework (the "Injector") is responsible for creating the calculator and handing it to the component.
// ✅ GOOD: Loose Coupling (With DI)
class ComponentA {
// We ask for the Calculator, we do not create it.
constructor(private calc: Calculator) {}
}Educational Note: This concept is often called Inversion of Control (IoC). Instead of the component controlling the creation of dependencies, the framework controls it.
Interesting Fact: Angular’s Dependency Injection system is hierarchical. This means you can have different instances of the same service at different levels of your component tree—a feature that distinguishes it significantly from other frontend frameworks like React (which relies heavily on Context or Props).
2. Creating and Injecting Services 🛠️
In Angular, a Service is a broad category encompassing any value, function, or feature that an application needs. A service is typically a class with a narrow, well-defined purpose.
Step 1: Generating a Service
To create a service, we use the Angular CLI. This ensures the correct boilerplate and testing files are generated.
ng generate service services/loggerOr the shorthand:
ng g s services/loggerStep 2: Anatomy of a Service
Let us look at the generated file logger.service.ts.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggerService {
constructor() { }
log(message: string) {
console.log(`[App Log]: ${message}`);
}
}@Injectable(): This decorator marks the class as a participant in the dependency injection system. It allows Angular to define how this class should be instantiated.providedIn: 'root': This metadata tells Angular to provide the service in the application root level (more on this in Subtopic 3).
Step 3: Injecting the Service
To use this logic in a component, we use Constructor Injection.
import { Component, OnInit } from '@angular/core';
import { LoggerService } from '../services/logger.service';
@Component({
selector: 'app-user-profile',
template: `<button (click)="saveUser()">Save</button>`,
standalone: true
})
export class UserProfileComponent {
// TypeScript shorthand syntax for declaring and initializing a property
constructor(private logger: LoggerService) {}
saveUser() {
// Business logic...
this.logger.log('User saved successfully.');
}
}When Angular creates UserProfileComponent, the DI system sees the LoggerService type in the constructor, looks for an existing instance, and provides it.
3. Providing Services: Root Level vs. Component Level 🌳
Understanding where you provide a service determines its lifecycle and scope. This is a critical distinction in Angular architecture.
Option A: Root Level (Singleton) - The Standard
When you leave providedIn: 'root' in the service decorator (the default behavior), the service becomes a Singleton.
- Singleton: Only one instance of the service exists for the entire application.
- Behavior: If
Component Awrites data to the service,Component Bsees that same data. - Optimization: Angular uses "Tree-shaking." If the service is not used in your code, it is removed from the final bundle build.
@Injectable({
providedIn: 'root' // ✅ Recommended for most cases
})
export class DataService { ... }Option B: Component Level (Sandboxed)
You can provide a service strictly to a specific component and its children by adding it to the providers array in the @Component decorator.
- Sandboxed: A new instance of the service is created every time the component is created.
- Behavior: The service instance is destroyed when the component is destroyed.
- Use Case: Ideal for services that need to handle state specific to a single instance of a widget (e.g., a tab component where every tab needs its own isolated state).
@Component({
selector: 'app-list-widget',
template: `...`,
providers: [ListService] // ⚠️ Creates a NEW instance for this component
})
export class ListWidgetComponent { ... }Critical Warning: If you accidentally provide a service in a Component when it is already provided in Root, you will create a "shadow" instance. The component will interact with its local instance, ignoring the global one, leading to confusing data desynchronization bugs.
4. Using Services to Share State Between Components 🔄
One of the most powerful uses of Services is acting as a "Single Source of Truth" for data sharing between components that are not directly related (e.g., siblings or cousins in the DOM tree).
The Industry Standard: RxJS BehaviorSubject
While simple properties work for static data, real-world applications use RxJS (Reactive Extensions for JavaScript) to handle state changes over time.
We use a pattern involving a private BehaviorSubject (which holds the value and allows writing) and a public Observable (which allows reading).
1. The Service (State Holder)
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
// 1. Define a private source (BehaviorSubject holds an initial value)
private cartCountSource = new BehaviorSubject<number>(0);
// 2. Expose it as a read-only Observable
currentCount$ = this.cartCountSource.asObservable();
// 3. Method to update the value
updateCartCount(count: number) {
this.cartCountSource.next(count);
}
}2. Component A (The Sender)
export class ProductComponent {
constructor(private cartService: CartService) {}
addToCart() {
this.cartService.updateCartCount(1); // Sends data
}
}3. Component B (The Receiver)
import { AsyncPipe } from '@angular/common';
@Component({
template: `<div>Cart Items: {{ count$ | async }}</div>`,
imports: [AsyncPipe], // Necessary for standalone
standalone: true
})
export class NavbarComponent {
// We can bind directly to the observable
count$ = this.cartService.currentCount$;
constructor(private cartService: CartService) {}
}Using the AsyncPipe in the template automatically subscribes to the data stream and unsubscribes when the component is destroyed, preventing memory leaks.
Modern Note (Angular v16+): While RxJS is the established standard, newer versions of Angular introduced Signals (
signal,computed) for state management. Signals offer a simpler syntax without Observables. However, RxJS remains the dominant requirement in enterprise Angular jobs today.
🧪 Hands-On Practice
- Create a
ThemeService. - Use a boolean flag (true = dark mode, false = light mode).
- Inject it into your
AppComponentto toggle a CSS class on the<body>tag. - Inject it into a
SettingsComponentto toggle the boolean via a button. - Observe how the change in
SettingsComponentimmediately affectsAppComponent.
🧠 Interesting Thought
Imagine if a restaurant kitchen had no specialized roles (no Services). The waiter (Component) would have to take the order, walk to the back, chop the vegetables, cook the steak, wash the dishes, and then serve the food. The restaurant would collapse. Services allow the waiter to simply request the food, trusting the Chef Service to handle the logic.
🔗 References & Further Reading
Challenge
Challenge: Implement a Shared State Service
You are building an application where two unrelated components, ProfileEditorComponent and HeaderDisplayComponent, need to access and react to the same piece of data: the current user's name. Your task is to create a service that acts as a single source of truth for this data and inject it into both components.
Requirements:
Create
UserDataService:- The service must be injectable and configured to be a singleton available throughout the entire application.
- Inside the service, use an RxJS
BehaviorSubjectto manage the user's name. This subject should be private to the service. - The initial value for the user's name must be
'Guest'. - Expose the user's name as a public
Observableso that components can subscribe to it but cannot push new values directly. - Create a single public method,
updateUserName(newName: string), which allows external components to update the user's name.
Update
ProfileEditorComponent:- Use constructor injection to get an instance of
UserDataService. - Implement the
saveNewName(name: string)method to call theupdateUserNamemethod on the injected service.
- Use constructor injection to get an instance of
Update
HeaderDisplayComponent:- Use constructor injection to get an instance of
UserDataService. - Initialize the public property
currentUserName$by assigning it the public nameObservablefrom the service.
- Use constructor injection to get an instance of
Expected result
Your final code should correctly implement a root-level service that manages state with an RxJS BehaviorSubject. Both components should inject this service via their constructors. The ProfileEditorComponent should use the service to update the state, while the HeaderDisplayComponent should subscribe to the state by referencing the service's public Observable.
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
// --- user-data.service.ts ---
@Injectable({
providedIn: 'root'
})
export class UserDataService {
private userName = new BehaviorSubject<string>('Guest');
public currentUserName$ = this.userName.asObservable();
constructor() { }
updateUserName(newName: string) {
this.userName.next(newName);
}
}
// --- profile-editor.component.ts ---
export class ProfileEditorComponent {
constructor(private userDataService: UserDataService) { }
saveNewName(name: string): void {
this.userDataService.updateUserName(name);
}
}
// --- header-display.component.ts ---
export class HeaderDisplayComponent {
public currentUserName$: Observable<string>;
constructor(private userDataService: UserDataService) {
this.currentUserName$ = this.userDataService.currentUserName$;
}
}