Sub topic 1
Why Angular Has Services
Prerequisites
This chapter assumes you know TypeScript classes and generics, Angular components and templates, standalone components with bootstrapApplication, and ES module imports. Some familiarity with Angular signals helps but is not required.
Why Angular Has Services
A service is a class that holds logic or state that more than one part of the app needs, such as data fetching, logging, or a shopping cart. Components should stay focused on the view. If two components each run new CartService(), each gets its own copy, so their state drifts apart. They also become tightly coupled to one concrete class, which makes them hard to test.
How Dependency Injection Works
Dependency injection (DI) means a consumer declares what it needs, and Angular supplies it. An injector is the object that creates instances and caches them. When a component asks for CartService, the injector checks whether it already has an instance. If it does not, the injector uses a provider (a recipe for building the value) to create one, then returns it.
Creating a Service with @Injectable
@Injectable({ providedIn: 'root' }) registers the service with the application's root injector. The service is tree-shakable: if nothing injects it, the build removes it.
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]);
}
}Injecting Services with inject() and Constructors
The inject() function retrieves a dependency. You can call it in a field initializer or in the constructor. Constructor parameters do the same thing through type metadata.
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);
}
// Equivalent constructor injection:
// constructor(protected readonly cart: CartService) {}Exercise
Two components each inject CartService, which uses providedIn: 'root'. One calls add('book'). What does the other component's count() show, and why?
Show answer
It shows 1. The root injector creates a single CartService instance and gives that same instance to both components, so they share the items signal.