Angular Signal-Based Architecture: Building a Smarter Shopping Cart

https://news.ycombinator.com/rss Hits: 2
Summary

In part one of this series, we explored how Angular Signals shift the reactive model away from the RxJS-centric approach we’ve relied on for years. We walked through the core API signal(), computed(), and effect() primitives, and demonstrated how they simplify state management by removing the need for subscriptions, teardown logic, and deeply nested observables. We also introduced a minimalist CartService that held cart items in a private signal and exposed a computed total price. In this second part, we’re going to build on that foundation. We’ll extend the CartService with a few critical capabilities such as removing items, clearing the cart, and tracking the number of products. We’ll also explore how this service integrates with Angular components and templates, using signals directly without the need for RxJS or the async pipe. Along the way, we’ll highlight how this approach enhances testability, performance, and debuggability. Our focus isn't to build the UI yet (that’s coming in the next article), but to mature the internal architecture so that it can support more advanced features like discounts, inventory checks, and persistence down the road. Our goal is to set up a fully reactive service layer that components can consume without worrying about subscriptions or manual change detection. Extending the CartService In part one, our CartService had the private _items = signal<CartItem[]>([]) and an addItem(item) method to push items into the cart. It also included a computed total that calculated the overall cost. That was a solid start, but minimal. Let’s now flesh it out with the typical operations you’d expect from a shopping cart. We’ll start with a method to remove items based on their product ID. With RxJS, this would typically involve grabbing the current value from a BehaviorSubject, cloning the array, and pushing the updated result using .next(). It’s also common to see developers keep a separate local array, mutate it directly, and then emit it again ...

First seen: 2025-10-04 13:58

Last seen: 2025-10-04 14:58