Services and inject()
A service is a class for shared work: holding the cart, talking to a server or saving settings. Many components can use the same service.
Components should focus on showing things. Work that isn't about display - talking to the server, keeping the cart, checking whether the user is logged in - belongs in services. That keeps components small, and lets many components share the same data: the header's cart badge and the cart page both read from one CartService.
Angular creates services for you and hands them to whoever asks - this is called dependency injection. You never write new CartService(); you call inject(CartService) and get the shared copy. In tests, you can inject a fake service instead.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
items = signal<string[]>([]);
add(item: string) {
this.items.update(list => [...list, item]);
}
}Get the service in any component with inject():
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-button',
template: `<button (click)="cart.add('Shoes')">Cart ({{ cart.items().length }})</button>`,
})
export class CartButton {
cart = inject(CartService);
}providedIn: 'root' means there is one shared copy of the service for the whole app.- Services hold shared logic and data.
@Injectable({ providedIn: 'root' })makes one app-wide copy.- Get a service with
inject().
