How can you manage state using services?
Managing state through services is a simple and powerful way to keep data under control without complex libraries.
What makes a service "manage state":
It:
- stores variables (for example,
user,cart,isLoading) - provides methods to change those variables
- gives values to components - directly or through a stream (
BehaviorSubject)
Example:
ts
@Injectable({ providedIn: 'root' })
export class CartService {
private cartItems = new BehaviorSubject<Product[]>([]);
cart$ = this.cartItems.asObservable();
add(item: Product) {
const current = this.cartItems.value;
this.cartItems.next([...current, item]);
}
clear() {
this.cartItems.next([]);
}
}The component simply subscribes:
ts
this.cartService.cart$.subscribe(items => this.cart = items);The end result:
- Components don't hold logic and data themselves - they just display it
- All changes go through one central place
- State lives on even if the component is destroyed
- Subscribers automatically receive updates
Conclusion: The service becomes a single store and dispatcher, where everything is transparent, reactive, and under control. For 90% of tasks, that's already enough.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.