惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
小众软件
小众软件
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
博客园 - 司徒正美
V
Visual Studio Blog
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
aimingoo的专栏
aimingoo的专栏
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
D
Docker
Vercel News
Vercel News
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
爱范儿
爱范儿
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Ngrx Signal Store
Maurizio8788 · 2026-06-17 · via DEV Community

In recent years, Angular has taken an important step toward a simpler and more declarative reactivity model with the introduction of Signals.

NgRx, which has long been the de facto standard for state management in complex Angular applications, followed this evolution by introducing Signal Store.

The goal is not to completely replace @ngrx/store, but to offer a lighter and more local alternative, designed for use cases where the classic Actions → Reducers → Selectors pattern feels excessive.

In this article, we'll see how to use NgRx Signal Store to build a reactive, typed store that integrates seamlessly with Angular components, drastically reducing boilerplate and improving code readability.

This tutorial is aimed at Angular developers who are already familiar with Signals and "classic" NgRx.

What is NgRx Signal Store

NgRx Signal Store introduces a different way of thinking about state compared to classic @ngrx/store.

A Signal Store:

  • is not based on Redux
  • does not use actions or reducers
  • does not require explicit selectors

Instead, the model revolves around three main concepts:

🧩 State

State is defined as a set of signals, typically using withState.

Each state property is immediately reactive and can be read directly by components.

🧠 Derived state

Derived state is defined using withComputed.

It is the conceptual equivalent of selectors, but with a more direct syntax and better integration with Angular's Signals system.

🔧 Methods

State changes and side effects (such as HTTP calls) are encapsulated in methods declared with withMethods.

This keeps the store logic in a single place, without having to orchestrate multiple files as in the traditional NgRx pattern.

In other words, a Signal Store resembles a strongly structured reactive service more than a pure Redux store.

This approach makes Signal Stores particularly suitable for:

  • local or feature state
  • small to medium-sized applications
  • reducing complexity in contexts where Redux would be overkill

Creating the first Signal Store

In this section we'll create a first Signal Store to manage a list of products and their loading state. For this tutorial I'll use:

  • Stackblitz
  • DummyJSON

Once we have a working Angular application, we first need to install @ngrx/signals using these commands:

ng add @ngrx/signals@latest

# or using npm

npm install @ngrx/signals --save

# or using yarn

yarn add @ngrx/signals

Creating a signal store is very simple — just use the signalStore() function. It accepts a series of features in the form of compatible functions.

Some of these we've already mentioned:

  • withState
  • withComputed
  • withMethods

Combining them lets us create a complete, typed store.

import { Product } from './products.model';
import {
  signalStore,
  withComputed,
  withMethods,
  withState,
} from '@ngrx/signals';

type ProductsState = {
  products: Product[];
  isLoading: boolean;
};

const initialState: ProductsState = {
  products: [],
  isLoading: false,
};

export const ProductsStore = signalStore(
  { providedIn: 'root' },
  withState(initialState),

  withComputed(() => {
    return {};
  }),
  withMethods((store) => ({}))
);

Let's briefly analyze what's happening:

  • ProductsState defines the shape of the state
  • initialState represents the initial state of the store
  • withState exposes each property as a signal
  • withComputed and withMethods are empty for now, but we'll fill them in shortly

As we can see, this configuration is enough to start using the signalStore.

Just like Angular services, the option:

{ providedIn: 'root' }

makes the Store injectable in components, services, and directives.

In the next step, we'll start adding derived state and methods to fetch data from a remote API.

Fetching data from an API and deriving state with signals

In all modern applications, SPAs (Single Page Applications) necessarily interface with some type of API to retrieve the data needed to build the user interface. The retrieved data must be stored so that it's accessible across one or more parts of the application, and sometimes it needs to be further processed.

To achieve all this, signalStore provides two specific functions:

  • withComputed — perfectly aligned with Angular's signal-based reactivity system
  • withMethods — allows us to write methods for manipulating the store or making HTTP calls to the API services from which we need to retrieve data

Starting from these concepts, here is the complete store with derived state and API data loading:

import { computed, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { Product } from './products.model';
import {
  patchState,
  signalStore,
  withComputed,
  withMethods,
  withState,
} from '@ngrx/signals';

type ProductsState = {
  products: Product[];
  isLoading: boolean;
};

const initialState: ProductsState = {
  products: [],
  isLoading: false,
};

export const ProductsStore = signalStore(
  { providedIn: 'root' },
  withState(initialState),

  withComputed((store) => ({
    productsCount: computed(() => store.products().length),
    expensiveProducts: computed(() =>
      store.products().filter((p) => p.price > 100)
    ),
  })),

  withMethods((store, http = inject(HttpClient)) => ({
    async loadProducts(): Promise<void> {
      patchState(store, { isLoading: true });
      try {
        const response = await firstValueFrom(
          http.get<{ products: Product[] }>('https://dummyjson.com/products')
        );
        patchState(store, { products: response.products, isLoading: false });
      } catch (error) {
        patchState(store, { isLoading: false });
        console.error('Error loading products', error);
      }
    },
  }))
);

Let's analyze what's new compared to the initial example:

  • patchState is NgRx Signal Store's function for updating state immutably. It accepts a partial object with only the properties to modify.
  • withComputed now returns two derived signals: productsCount (total number of products) and expensiveProducts (products with a price above 100).
  • withMethods includes loadProducts, which handles the entire HTTP call lifecycle: activates the loader, updates products on response, and restores the loader in case of error.

Using the Store in a component

With our store ready, injecting it into a component is straightforward, just like you would with a regular Angular service.

import { Component, OnInit, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { ProductsStore } from './products.store';

@Component({
  selector: 'app-products',
  standalone: true,
  imports: [CurrencyPipe],
  template: `
    @if (store.isLoading()) {
      <p>Loading...</p>
    } @else {
      <p>Total products: {{ store.productsCount() }}</p>
      <ul>
        @for (product of store.products(); track product.id) {
          <li>{{ product.title }} — {{ product.price | currency:'EUR' }}</li>
        }
      </ul>
    }
  `,
})
export class ProductsComponent implements OnInit {
  readonly store = inject(ProductsStore);

  ngOnInit(): void {
    this.store.loadProducts();
  }
}

Notice how the template uses the signals exposed by the store directly:

  • store.isLoading() — boolean signal to show the loading state
  • store.products() — signal with the product list
  • store.productsCount() — derived signal with the total number of products

No async pipe or subscribe is needed: signals update automatically and Angular detects changes through the new signal-based change detection strategy.

From firstValueFrom to rxMethod: a more reactive approach

The implementation with async/await and firstValueFrom works perfectly, but NgRx Signal Store offers a more powerful and idiomatic alternative for handling methods that work with observables: rxMethod.

rxMethod is available in @ngrx/signals/rxjs-interop and allows defining methods that accept values, signals, or observables as input, integrating natively with the RxJS pipeline.

Before using it, you need to install the @ngrx/operators package:

# using npm
npm install @ngrx/operators

# or using yarn
yarn add @ngrx/operators

What is tapResponse

tapResponse is an operator provided by @ngrx/operators, specifically designed to handle responses in NgRx store reactive pipelines. It is used instead of catchError for one fundamental reason: it does not complete the outer stream on error.

This is crucial when rxMethod is connected to a long-lived observable, such as a reactive search field. With catchError, the first error would complete the entire stream and the method would stop responding to subsequent inputs. With tapResponse, the stream stays alive and the method keeps working correctly.

Its syntax resembles that of subscribe:

tapResponse({
  next: (value) => { /* success handling */ },
  error: (error) => { /* error handling */ },
  finalize: () => { /* optional: always runs at completion */ },
})

Updated store with rxMethod

Here's how to rewrite ProductsStore replacing firstValueFrom with rxMethod and tapResponse:

import { computed, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { pipe, switchMap, tap } from 'rxjs';
import { tapResponse } from '@ngrx/operators';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { Product } from './products.model';
import {
  patchState,
  signalStore,
  withComputed,
  withMethods,
  withState,
} from '@ngrx/signals';

type ProductsState = {
  products: Product[];
  isLoading: boolean;
};

const initialState: ProductsState = {
  products: [],
  isLoading: false,
};

export const ProductsStore = signalStore(
  { providedIn: 'root' },
  withState(initialState),

  withComputed((store) => ({
    productsCount: computed(() => store.products().length),
    expensiveProducts: computed(() =>
      store.products().filter((p) => p.price > 100)
    ),
  })),

  withMethods((store, http = inject(HttpClient)) => ({
    loadProducts: rxMethod<void>(
      pipe(
        tap(() => patchState(store, { isLoading: true })),
        switchMap(() =>
          http.get<{ products: Product[] }>('https://dummyjson.com/products').pipe(
            tapResponse({
              next: (res) =>
                patchState(store, { products: res.products, isLoading: false }),
              error: () =>
                patchState(store, { isLoading: false }),
            })
          )
        )
      )
    ),
  }))
);

The main changes compared to the firstValueFrom version:

  • No more async/await or try/catch: flow management is entirely declarative via RxJS operators.
  • rxMethod<void> indicates the method requires no parameters. By passing a type other than void, the method can accept a value, signal, or observable as input, becoming automatically reactive.
  • switchMap automatically cancels the previous HTTP call if loadProducts is invoked before the response arrives, avoiding out-of-order responses.
  • tapResponse handles success and error without interrupting the stream, ensuring the method continues to work correctly even after a network error.

The component requires no changes: store.loadProducts() is called exactly as before.

Conclusion

NgRx Signal Store represents an important step toward more modern and maintainable Angular development. Compared to classic @ngrx/store, it offers a lighter approach with less boilerplate, declarative state contained in a single file, and full native integration with Angular's Signals.

It is the ideal tool for managing the state of features or specific sections of an application, without sacrificing the structure and testability expected from an NgRx solution.

The complete project will be available on Stackblitz soon — I'll update this article as soon as it's ready.