Using Angular Services for Simple State Management
An Angular service acts like a central data store. Components subscribe to it for data, rather than owning state, keeping data consistent across views. It's ideal for sharing user info or cart contents.
WHY IT EXISTS: In a component-based framework, components are created and destroyed as users navigate. If a component holds important data (like a shopping cart), that data is lost when the component is destroyed. We need a way to store data that outlives any single component.
THE MENTAL MODEL: Think of an Angular service as a dedicated data manager for your application. It's a singleton object—meaning there's only one instance of it—that lives for the entire duration of the user's session. Components don't own the data; they are just temporary viewers. They ask the service for the current state and tell the service about any changes.
HOW IT WORKS: You create a class decorated with @Injectable({ providedIn: 'root' }). This tells Angular's dependency injection system to create a single instance of this service for the entire application. Inside the service, you use private properties to hold the state and public methods to get or update that state. To make it reactive, you often expose the state through an RxJS BehaviorSubject. Components can then subscribe to this observable. When the state changes, the BehaviorSubject pushes the new value to all subscribed components, automatically updating their views.
WHEN TO USE IT: Use services for state management in small to medium-sized Angular applications. It's a great fit for managing cross-component information like the currently logged-in user, contents of a shopping cart, or application-wide settings like a dark theme. It's built-in, lightweight, and easy to understand.
WHEN NOT TO USE IT: As application complexity grows, managing state with services can become unwieldy. If you have complex workflows, need undo/redo functionality, or want to track a history of state changes for debugging (time-travel debugging), a dedicated state management library like NgRx or Akita is a better choice. These libraries provide more structure at the cost of more boilerplate.
ONE CANONICAL EXAMPLE: A shopping cart service. The service would have a private array of items and a public method addToCart(item). A ProductListComponent would call this method. A separate CartComponent would subscribe to an observable from the service that emits the current list of items. Both components interact with the service, not each other, ensuring a single source of truth for the cart's contents.
Read the original → w3schools.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.