Sub topic 1
Why Angular Has Services
Components display data and react to user input. Real applications also fetch data, cache it, log errors, and share state between screens. A service holds that logic so no single component has to own it.
Prerequisites
This chapter assumes you are comfortable with:
- TypeScript classes, interfaces, and generics
- Angular components and templates
- Standalone components and
bootstrapApplication - ES module
importandexport
Some familiarity with RxJS Observables or Angular signals helps later in the tutorial, but you don't need it yet.
What a service is
A service is a plain TypeScript class with one focused job. Some examples:
CartServicekeeps the items a shopper has selected.ApiClientwraps HTTP calls to your backend.Loggersends messages to the console or a monitoring tool.
A service has no template and no selector. It renders nothing. It exists so that components, directives, and other services can call its methods and read its state.
The problem services solve
Suppose two components both need the shopping cart. The obvious first attempt is to create the cart inside each component with new.
import { Component } from '@angular/core';
export class CartStore {
items: string[] = [];
add(item: string): void {
this.items.push(item);
}
}
@Component({
selector: 'app-product',
standalone: true,
template: `<button (click)="cart.add('Book')">Add book</button>`
})
export class ProductComponent {
cart = new CartStore();
}
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ cart.items.length }}`
})
export class CartBadgeComponent {
cart = new CartStore();
}This compiles and runs, but the badge always shows Items: 0. Each component built its own CartStore, so they hold two separate arrays. Manual instantiation causes three problems:
| Problem | What goes wrong |
|---|---|
| No sharing | Each `new` creates a separate instance, so state does not sync between components. |
| Tight coupling | The component picks the concrete class itself. Swapping in another implementation means editing every consumer. |
| Hard testing | A test cannot replace `CartStore` with a fake without changing the component's code. |
When CartStore gains its own dependencies, such as an HTTP client and a logger, every consumer must also build those and pass them in. The construction code spreads across the app.
Letting Angular supply the instance
Angular's answer is dependency injection (DI). A component declares that it needs a CartStore, and Angular's injector creates the instance and hands it over. The injector decides how many instances exist and who shares them. By default, the whole app shares one instance.
With DI, the components stay small. They describe what they need and leave the construction to Angular. Tests can tell the injector to supply a fake, and the component code does not change.
Common mistakes at this stage
- Putting fetch and cache logic in components. The component grows, and other screens copy the logic instead of reusing it.
- Expecting state to sync after using
new. Everynewcreates a separate object. Sharing only happens when the same instance reaches every consumer. - Treating services as global variables. A service should expose a clear API made of methods and read-only state. Consumers should not mutate its internals directly.
The next chapter explains how the injector works: how it finds a recipe for a dependency, creates the instance, and caches it.
Exercise
In the CartStore example, the badge always shows "Items: 0" after clicking "Add book". Explain why, and name the property of dependency injection that fixes it.
Show answer
Each component calls new CartStore(), so ProductComponent adds to one array while CartBadgeComponent reads a different, empty array. Dependency injection fixes this because the injector creates one instance and gives that same instance to every consumer that asks for it, so both components share the same state.
Exercise
Give two reasons, besides sharing state, to move logic from a component into a service.
Show answer
First, it decouples consumers from the concrete class, so the implementation can be swapped in one place. Second, it makes testing easier, because a test can tell the injector to supply a fake instead of the real service. A third reason is reuse: several components can call the same logic without copying it.