Creating a Shared Data Service
A shared data service keeps its state in a private signal, shows it to components read-only with asReadonly() and computed values, and changes it only through its own methods. Every component that injects it sees the same, up-to-date data.
Journeyman · Angular · Updated
After this lesson you can
- Share state between components with a service that holds signals and exposes them read-only
Key takeaways
- Keep a shared service's state in a
privatesignal, so only the service can change it. - Show the state to components read-only, with
asReadonly()andcomputedvalues such ascountandtotal. - Change the state only through the service's own methods, such as
add,removeandclear. - Every component that injects
Cartgets the same instance, and because the state is in signals, each one updates the moment it changes.
Here's the cart from the last lesson, as a service that any component can use.
The service
import { computed, Service, signal } from '@angular/core';
export interface CartItem {
productId: number;
productName: string;
unitPrice: number;
}
@Service()
export class Cart {
private readonly itemList = signal<CartItem[]>([]);
readonly items = this.itemList.asReadonly();
readonly count = computed(() => this.itemList().length);
readonly total = computed(() => this.itemList().reduce((sum, item) => sum + item.unitPrice, 0));
add(item: CartItem) {
this.itemList.update(items => [...items, item]);
}
remove(productId: number) {
this.itemList.update(items => items.filter(item => item.productId !== productId));
}
clear() {
this.itemList.set([]);
}
}
The pattern is encapsulation, as with C# classes:
- The state is private.
itemListis aprivatesignal: only the service can change it. - Components get read-only views.
asReadonly()gives a signal you can read but notset, andcountandtotalarecomputeds. - Changes go through methods.
add,removeandclearare the only ways in, so the service is always in charge of its data.
Two components, one cart
The product card adds:
import { Component, inject, input } from '@angular/core';
import { Cart, CartItem } from './cart';
@Component({
imports: [],
selector: 'app-buy-button',
template: `<button class="btn btn-primary btn-sm" (click)="cart.add(product())">Add to cart</button>`,
})
export class BuyButton {
readonly product = input.required<CartItem>();
protected readonly cart = inject(Cart);
}
The header shows:
import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { Cart } from './cart';
@Component({
imports: [CurrencyPipe],
selector: 'app-cart-badge',
template: `<span class="badge text-bg-dark">Cart: {{ cart.count() }} ({{ cart.total() | currency }})</span>`,
})
export class CartBadge {
protected readonly cart = inject(Cart);
}
Put a CartBadge in the header and BuyButtons on the product cards, anywhere in the tree. Click Add to cart for Chai ($18) and Konbu ($6), and the badge says Cart: 2 ($24.00). Neither component knows the other exists: both just inject Cart, and get the same instance.
Because the state is in signals, every component that reads it updates the moment it changes, wherever it is on the page.
Do it: let the cart remove an item and add up its total
Here is the Cart as a plain JavaScript class, without Angular's signals, so you can try its methods in the box. add is written. Two methods are missing: remove and total.
The cart keeps its items in items, a list. Each item is an object with three properties:
productId: the product's id, a number (13).productName: its name ('Konbu').unitPrice: its price, a number (6).
For example:
const cart = new Cart();
cart.add({ productId: 1, productName: 'Chai', unitPrice: 18 });
cart.add({ productId: 13, productName: 'Konbu', unitPrice: 6 });
cart.add({ productId: 14, productName: 'Tofu', unitPrice: 23.25 });
cart.remove(13);
| Step | Items in the cart | total() |
|---|---|---|
After the three adds |
Chai, Konbu, Tofu | 18 + 6 + 23.25 = 47.25 |
After remove(13) |
Chai, Tofu | 18 + 23.25 = 41.25 |
So after these lines, cart.total() returns 41.25.
Your job: write two methods in the Cart class.
remove(productId)takes out the item with thatproductId, and keeps the other items in their order.- If no item has that
productId,removechanges nothing. total()returns the sum of every item'sunitPrice.- An empty cart's
total()is0.
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
1 question to try on the lesson page.
So what
A shared data service is a private signal, a few read-only views of it, and methods to change it. Inject it anywhere, and every part of the app sees one truth.