Sub topic 1
Why Angular Has Services
An Angular component is meant to manage one piece of the screen: it renders a template, reacts to user events, and passes data to child components. Real applications also need to fetch data, keep a shopping cart in sync across pages, log errors, and read configuration. If all of that lives inside components, the code gets duplicated, components become hard to test, and pieces of the UI stop agreeing with each other. Angular puts this kind of shared logic in services and uses dependency injection to hand them to the code that needs them.
This chapter covers the problem services solve and what makes a class a good service. It also explains why Angular hands services to components instead of letting each component construct its own. The mechanics of dependency injection start in the next chapter.
Prerequisites
This chapter assumes you are comfortable with:
- TypeScript classes, interfaces, and generics
- Angular components and templates, including interpolation and event binding
- Standalone components and starting an app with
bootstrapApplication - ES module
importandexport
Some familiarity with Angular signals or RxJS Observables helps but is not required. The examples use signals in a minimal way.
The problem: logic trapped in components
Picture a store with two components. A header badge shows how many items are in the cart. A product list has "Add to cart" buttons. Both need the cart.
A first attempt often puts the cart directly in each component:
import { Component } from '@angular/core';
@Component({
selector: 'app-product-list',
standalone: true,
template: `<button (click)="add('Book')">Add Book</button>`
})
export class ProductListComponent {
items: string[] = [];
add(item: string): void {
this.items = [...this.items, item];
}
}
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ items.length }}`
})
export class CartBadgeComponent {
items: string[] = [];
}This compiles and runs, but the badge always shows Items: 0. Each component owns a separate items array, so clicking the button changes an array the badge never sees. You could fix this by passing data through @Input() and @Output() from a shared parent. That works for neighbours, but it breaks down as the app grows. The badge sits in the header, the product list sits deep inside a routed page, and every component between them ends up forwarding cart data it does not care about. This is often called prop drilling.
Components also mix concerns in this design. The product list now knows how a cart is stored, and if the cart later needs to persist to localStorage or sync with a server, every component that touches it must change.
What a service is
A service is a plain TypeScript class with a narrow, well-defined job that does not involve rendering. Angular adds no special base class. What makes it a service is how it is used: many consumers share it, and Angular creates it and delivers it to them.
Common service responsibilities include:
- Holding shared state, such as the current user, cart contents, or feature flags
- Talking to the outside world through HTTP calls, WebSockets, or browser storage
- Wrapping cross-cutting concerns like logging, analytics, and error reporting
- Encapsulating business rules, for example price calculation or validation
Moving the cart into a service gives it one home:
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly items = signal<string[]>([]);
readonly count = computed(() => this.items().length);
add(item: string): void {
this.items.update(list => [...list, item]);
}
}The items signal is private, so consumers cannot replace the array directly. They call add() and read count. The @Injectable({ providedIn: 'root' }) decorator tells Angular it may create this class and share one instance across the application. Chapter 3 explains that decorator in detail.
The split of responsibilities looks like this:
| Concern | Belongs in a component | Belongs in a service |
|---|---|---|
| Rendering markup and handling DOM events | Yes | No |
| State that only one component instance uses (an open/closed toggle) | Yes | Usually no |
| State several components must agree on (cart, session) | No | Yes |
| HTTP requests and storage access | No | Yes |
| Business rules reused across screens | No | Yes |
| Formatting a value for one template | Yes, or a pipe | Rarely |
Why not just call `new`?
Once the cart is a class, the obvious next step is to construct it:
import { Component } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ cart.count() }}`
})
export class CartBadgeComponent {
protected readonly cart = new CartService();
}This brings back the original bug in a new form. Every new CartService() creates a separate cart, so the badge and the product list still disagree. Manual construction causes other problems too.
Problem 1: no sharing
To share one instance with new, you would need a global variable or a hand-written singleton (CartService.instance). Both approaches hide the dependency, make it hard to reset between tests, and make it impossible to have a separate instance for one part of the UI when you need one.
Problem 2: the consumer must know how to build its dependencies
Suppose CartService later needs an HTTP client and a logger:
export class CartService {
constructor(private http: HttpClient, private logger: Logger) {}
}Every new CartService(...) call must now be updated to supply those arguments. The component then has to know how to build an HttpClient, which itself has dependencies. Construction details spread through the whole codebase, and a change to one constructor causes edits in every file that builds the class.
Problem 3: hard to test
A component that calls new CartService() is welded to the real implementation. In a unit test you cannot swap in a fake cart with a fixed count, so the test exercises the real service and anything it calls, such as the network. Chapter 14 shows how dependency injection makes this swap a one-line change.
Problem 4: no control over lifetime
Something has to decide when a service is created and when it is destroyed. With new, the answer is "whenever some code happens to run", which makes cleanup of subscriptions or timers unreliable.
The alternative: ask, don't build
Dependency injection (DI) reverses the relationship. Instead of constructing its dependencies, a class declares what it needs, and Angular supplies a suitable instance. The component asks for a CartService and does not care how it is built or who else is using it:
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-badge',
standalone: true,
template: `Items: {{ cart.count() }}`
})
export class CartBadgeComponent {
protected readonly cart = inject(CartService);
}Because CartService is provided in root, every component that calls inject(CartService) receives the same instance. The badge and the product list now share one cart, and neither one builds it.
With DI, the costs of manual construction go away:
- Sharing comes from where the service is provided, not from globals.
- Construction is the injector's job. When
CartServicegains dependencies, consumers do not change. - Testing means telling the injector to hand out a fake.
- Lifetime follows the injector that created the instance. Root services live as long as the app, and component-scoped services are destroyed with their component.
Common mistakes when starting with services
- Calling
newon an injectable class. It compiles, but you get a private copy that skips DI and does not share state. If a class has@Injectable, ask for it withinject()instead of constructing it. - Making services that do everything. A single
AppServiceholding user, cart, settings, and HTTP calls becomes as tangled as the fat component it replaced. Give each service one area of responsibility. - Exposing mutable state directly. A public
items: string[]lets any component mutate the cart without the service knowing. Keep state private and expose read-only signals or Observables plus methods that change it. Chapter 10 covers this in depth. - Moving purely visual state into services. Whether one dropdown is open is usually that component's business. Putting it in a root service makes it shared by accident.
- Assuming a service is always a singleton.
providedIn: 'root'gives one instance per application, but a service listed in a component'sprovidersarray gets a fresh instance per component. Chapters 8 and 9 explain how the injector hierarchy decides this.
Edge cases worth knowing early
- Services can depend on other services.
CartServicecan inject aLogger, and Angular resolves the whole chain. A cycle (A needs B, B needs A) throws a circular dependency error at runtime. - Not every dependency is a class. Configuration objects, URLs, and feature flags are injectable too, through
InjectionToken(Chapter 7). - Injection needs a context.
inject()only works during construction of a class that Angular creates, or in a few other specific places. Calling it inside a click handler fails. Chapter 13 covers the rules.
Exercise
Two components each declare private store = new SettingsService();. A user changes the theme in one component, and the other does not update. Explain the cause and the fix.
Show answer
Each new call creates a separate SettingsService instance, so the two components hold different state. Mark the class with @Injectable({ providedIn: 'root' }) and obtain it with inject(SettingsService) in both components. The root injector then hands both of them the same instance.
Exercise
Sort these into "component" or "service": (a) whether a tooltip is visible, (b) the logged-in user's profile, (c) a function that calculates sales tax used on three pages, (d) the HTTP call that loads products.
Show answer
(a) component, because it is local visual state. (b) service, because many parts of the app share it. (c) service, because the business rule is reused. (d) service, because it is I/O that should be shared and replaceable in tests.
Exercise
CartService gains a constructor parameter for a Logger. Why does a component that uses inject(CartService) need no changes, while one that uses new CartService() does?
Show answer
With inject(), the injector builds CartService and resolves its Logger dependency itself, so the consumer never sees the constructor. With new, the consumer calls the constructor directly and must now create and pass a Logger, so every call site has to change.