1. 前端状态治理选型决策矩阵

技术维度NgRx SignalStore + Events传统 NgRx Redux StoreService + BehaviorSubject组件本地 Signals
底层响应模型Angular Signals 原生RxJS Observable 异步流RxJS Subject 事件多播细粒度 signal() / computed()
样板代码开销极简:函数式可插拔组合切片繁重:分立 Actions/Reducers/Effects较低:但缺乏规范易演化为大泥球无额外开销
单向流与溯源强契约:依托 eventGroup 追踪事实强:严格遵循 Redux 调度链路弱:随意调用 next() 导致竞态失控仅局限于当前组件内部拓扑
异步副作用控制清晰:withEventHandlers 串联 RxJS复杂:通过 @Injectable() Effects 拦截手动混杂在服务方法内部容易在 effect() 中误触发异步请求
局部渲染性能微任务精准刷新:无 Zone.js 开销依赖 OnPush 与异步管道触发标记需手动管理取消订阅与脏检查模板节点级别更新
首选应用场景全局共享状态(Auth、Cart、Preferences)大型多团队协作的存量 Redux 系统极简跨组件通信临时过渡方案单个组件专属的视图控制开关

2. NgRx SignalStore + Events 生产级状态中枢范式

事件契约与状态定义 (auth.events.ts & auth.state.ts)

typescript
import { eventGroup, type } from '@ngrx/signals/events';
import { SigninRequest, SignupRequest, UserInfo } from '../../../shared/models/auth';
 
export const authPageEvents = eventGroup({
  source: 'Auth Page',
  events: {
    signinSubmitted: type<SigninRequest>(),
    signupSubmitted: type<SignupRequest>(),
    logoutClicked: type<void>()
  }
});
 
export const authApiEvents = eventGroup({
  source: 'Auth API',
  events: {
    signinSuccess: type<{ user: UserInfo; accessToken: string; refreshToken: string }>(),
    signinFailure: type<{ error: string }>(),
    signupSuccess: type<void>(),
    signupFailure: type<{ error: string }>()
  }
});
 
export interface AuthState {
  user: UserInfo | null;
  accessToken: string | null;
  refreshToken: string | null;
  loading: boolean;
  error: string | null;
}
 
export const initialAuthState: AuthState = {
  user: null,
  accessToken: null,
  refreshToken: null,
  loading: false,
  error: null
};

核心状态中枢实现 (auth.store.ts)

typescript
import { inject, computed } from '@angular/core';
import { Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, exhaustMap, map, of } from 'rxjs';
import { signalStore, withState, withComputed, withMethods, patchState } from '@ngrx/signals';
import { Events, withEventHandlers, withReducer, on } from '@ngrx/signals/events';
import { initialAuthState } from './auth.state';
import { authPageEvents, authApiEvents } from './auth.events';
import { AuthService } from '../services/auth.service';
 
export const AuthStore = signalStore(
  { providedIn: 'root' },
  withState(initialAuthState),
 
  // 1. 纯函数状态转移(Reducers)
  withReducer(
    on(authPageEvents.signinSubmitted, authPageEvents.signupSubmitted, () => ({
      loading: true,
      error: null
    })),
    on(authApiEvents.signinSuccess, (event) => ({
      user: event.payload.user,
      accessToken: event.payload.accessToken,
      refreshToken: event.payload.refreshToken,
      loading: false,
      error: null
    })),
    on(authApiEvents.signinFailure, authApiEvents.signupFailure, (event) => ({
      loading: false,
      error: event.payload.error
    })),
    on(authPageEvents.logoutClicked, () => ({
      ...initialAuthState
    }))
  ),
 
  // 2. 派生计算信号(Computed)
  withComputed((store) => ({
    isAuthenticated: computed(() => store.accessToken() !== null),
    currentUser: computed(() => store.user()),
    userDisplayName: computed(() => {
      const u = store.user();
      return u ? `${u.firstName} ${u.lastName}` : '';
    })
  })),
 
  // 3. 异步副作用编排(Event Handlers)
  withEventHandlers((store, events = inject(Events), authService = inject(AuthService)) => ({
    signin$: events.on(authPageEvents.signinSubmitted).pipe(
      exhaustMap((event) =>
        authService.signin(event.payload).pipe(
          map((res) => authApiEvents.signinSuccess(res)),
          catchError((err: { message: string }) =>
            of(authApiEvents.signinFailure({ error: err.message || 'Authentication failed' }))
          )
        )
      )
    )
  })),
 
  // 4. 路由跳转与指令式方法
  withMethods((store, events = inject(Events), router = inject(Router)) => {
    events.on(authApiEvents.signinSuccess).pipe(takeUntilDestroyed()).subscribe(() => {
      router.navigate(['/books']);
    });
 
    return {
      clearError: () => patchState(store, { error: null })
    };
  })
);

3. 组件层消费 SignalStore 生产范式

typescript
import { Component, inject, OnInit } from '@angular/core';
import { injectDispatch } from '@ngrx/signals/events';
import { AuthStore } from '../../store/auth.store';
import { authPageEvents } from '../../store/auth.events';
import { SigninRequest } from '../../../../shared/models/auth';
import { SigninForm } from '../../components/signin-form/signin-form';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
 
@Component({
  selector: 'app-signin-page',
  standalone: true,
  imports: [SigninForm, MatProgressSpinnerModule],
  template: `
    <div class="signin-container p-6 max-w-md mx-auto">
      <h1 class="text-2xl font-bold mb-4">用户登录</h1>
 
      @if (store.error()) {
        <div class="error-banner p-3 mb-4 bg-red-100 text-red-700 rounded">
          {{ store.error() }}
        </div>
      }
 
      <app-signin-form (signinComplete)="onSignin($event)" />
 
      @if (store.loading()) {
        <div class="spinner-overlay flex justify-center mt-4">
          <mat-spinner diameter="32" />
        </div>
      }
    </div>
  `
})
export class SigninPage implements OnInit {
  protected readonly store = inject(AuthStore);
  protected readonly dispatch = injectDispatch(authPageEvents);
 
  ngOnInit(): void {
    this.store.clearError();
  }
 
  onSignin(credentials: SigninRequest): void {
    // 组件不处理任何 HTTP 请求或路由跳转,纯粹派发意图事件
    this.dispatch.signinSubmitted(credentials);
  }
}

4. Signals 状态治理避坑清单 (Do's & Don'ts)

错误实践 (Don't)正确实践 (Do)
在 effect() 内部直接触发异步 HTTP 请求并等待返回。使用 toObservable 将 Signal 转换为 RxJS 数据流,配合 exhaustMap 或 switchMap 管理异步并发与竞态。
在 Reducer 或 patchState 中直接修改嵌套对象属性(破坏不可变性)。遵循不可变原则,返回新的 Partial State 字典,或使用展开运算符 { ...state, user: { ...state.user, role } }。
在 Reducer 或 EventHandler 内部直接调用 router.navigate() 产生路由副作用。将路由跳转声明在 withMethods 中对事件流的独立订阅管道中,保持 Reducer 与 EventHandler 纯粹。
为每个组件私有状态都建立全局 SignalStore。区分全局应用级状态(如认证、购物车)与组件内部私有状态(本地 signal() 控制显隐)。
在模板中反复直接调用无缓存的高开销计算函数。使用 computed() 封装派生逻辑,享有惰性求值与依赖项变动前结果缓存的红利。