1. CRUD 状态流与并发治理决策矩阵

技术维度选型方案替代方案决策依据
分页契约适配PaginatedResponse<T> 映射模型扁平数组 + 前端切片计算对齐 Spring Data Page<T> 元数据(总条数/页数/当前页),降低客户端内存占用。
读写不对称性Book(含嵌套对象)与 BookRequest(标量外键)分离前后端共用单一宽松类型杜绝提交包含循环引用或冗余实体的大对象,契约语义清晰明确。
并发流线控制读操作 switchMap / 写操作 exhaustMap统一使用 mergeMap 或 concatMap检索与分页自动取消在途旧请求;写操作在提交完成前忽略重复触发,天然防重。
变更新鲜度保证声明式事件流水线 reloadAfterMutation$本地 Reducer 手动拼接追加数组确保排序规则、分页总条数与关联统计完全由数据库计算裁决,杜绝数据撕裂。
跨域级联选择视图层直接注入 AuthorStore 活信号局部组件各自分立拉取作者数据消除重复 HTTP 请求,利用全局 SignalStore 缓存实现多模态框状态实时同步。

2. 生产级 SignalStore:完整 CRUD 与自动刷新管线

typescript
import { computed, inject } from '@angular/core';
import { signalStore, withState, withComputed } from '@ngrx/signals';
import { withReducer, withEventHandlers, Events, on } from '@ngrx/signals/events';
import { switchMap, map, catchError, of, exhaustMap } from 'rxjs';
import { normalizeApiErrorMessage } from '../../../../shared/utils/error-message';
import { AuthorService } from '../../services/author.service';
import { authorPageEvents, authorApiEvents } from './author.events';
import { initialAuthorState } from './author.state';
 
export const AuthorStore = signalStore(
  { providedIn: 'root' },
  withState(initialAuthorState),
 
  withReducer(
    // 分页加载与检索
    on(authorPageEvents.loadAuthors, (event) => ({
      loading: true,
      error: null,
      searchTerm: '',
      currentPage: event.payload.page,
      pageSize: event.payload.size,
    })),
    on(authorApiEvents.loadSuccess, (event) => ({
      authors: event.payload.authors,
      totalElements: event.payload.totalElements,
      totalPages: event.payload.totalPages,
      loading: false,
      error: null,
    })),
    on(authorApiEvents.loadFailure, (event) => ({
      loading: false,
      error: event.payload.error,
    })),
 
    // 变动过渡态
    on(authorPageEvents.createSubmitted, () => ({ loading: true, error: null })),
    on(authorApiEvents.createSuccess, () => ({ loading: false, error: null })),
    on(authorApiEvents.createFailure, (event) => ({ loading: false, error: event.payload.error })),
 
    on(authorPageEvents.updateSubmitted, () => ({ loading: true, error: null })),
    on(authorApiEvents.updateSuccess, () => ({ loading: false, error: null })),
    on(authorApiEvents.updateFailure, (event) => ({ loading: false, error: event.payload.error })),
 
    on(authorPageEvents.deleteConfirmed, () => ({ loading: true, error: null })),
    on(authorApiEvents.deleteSuccess, () => ({ loading: false, error: null })),
    on(authorApiEvents.deleteFailure, (event) => ({ loading: false, error: event.payload.error }))
  ),
 
  withComputed((store) => ({
    hasAuthors: computed(() => store.authors().length > 0),
    isSearching: computed(() => store.searchTerm().length > 0),
    authorCount: computed(() => store.totalElements()),
  })),
 
  withEventHandlers((store, events = inject(Events), authorService = inject(AuthorService)) => ({
    // 读操作:switchMap 自动取消在途旧请求
    load$: events.on(authorPageEvents.loadAuthors).pipe(
      switchMap((event) =>
        authorService.getPaged(event.payload.page, event.payload.size).pipe(
          map((res) =>
            authorApiEvents.loadSuccess({
              authors: res.content,
              totalElements: res.totalElements,
              totalPages: res.totalPages,
            })
          ),
          catchError((err) =>
            of(authorApiEvents.loadFailure({ error: normalizeApiErrorMessage(err, 'Failed to load authors') }))
          )
        )
      )
    ),
 
    // 写操作:exhaustMap 阻止并发重复提交
    create$: events.on(authorPageEvents.createSubmitted).pipe(
      exhaustMap((event) =>
        authorService.create(event.payload).pipe(
          map((author) => authorApiEvents.createSuccess({ author })),
          catchError((err) =>
            of(authorApiEvents.createFailure({ error: normalizeApiErrorMessage(err, 'Failed to create author') }))
          )
        )
      )
    ),
 
    update$: events.on(authorPageEvents.updateSubmitted).pipe(
      exhaustMap((event) => {
        const { id, ...data } = event.payload;
        return authorService.update(id, data).pipe(
          map((author) => authorApiEvents.updateSuccess({ author })),
          catchError((err) =>
            of(authorApiEvents.updateFailure({ error: normalizeApiErrorMessage(err, 'Failed to update author') }))
          )
        );
      })
    ),
 
    delete$: events.on(authorPageEvents.deleteConfirmed).pipe(
      exhaustMap((event) =>
        authorService.delete(event.payload.id).pipe(
          map(() => authorApiEvents.deleteSuccess({ id: event.payload.id })),
          catchError((err) =>
            of(authorApiEvents.deleteFailure({ error: normalizeApiErrorMessage(err, 'Failed to delete author') }))
          )
        )
      )
    ),
 
    // 变更新鲜度管线:成功后自动重载当前分页,保持多端数据精确一致
    reloadAfterCreate$: events.on(authorApiEvents.createSuccess).pipe(
      map(() => authorPageEvents.loadAuthors({ page: store.currentPage(), size: store.pageSize() }))
    ),
    reloadAfterUpdate$: events.on(authorApiEvents.updateSuccess).pipe(
      map(() => authorPageEvents.loadAuthors({ page: store.currentPage(), size: store.pageSize() }))
    ),
    reloadAfterDelete$: events.on(authorApiEvents.deleteSuccess).pipe(
      map(() => authorPageEvents.loadAuthors({ page: store.currentPage(), size: store.pageSize() }))
    ),
  }))
);

3. 跨 Store 响应式级联选择与不对称契约适配

typescript
import { Component, inject } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { injectDispatch } from '@ngrx/signals/events';
import { AuthorStore } from '../../store/author-store/author.store';
import { authorPageEvents } from '../../store/author-store/author.events';
import { Book, BookRequest } from '../../../shared/models/book';
 
export class BookForm {
  private fb = inject(FormBuilder);
  readonly authorStore = inject(AuthorStore);
  private readonly dispatch = injectDispatch(authorPageEvents);
 
  // 表单仅持有标量外键 authorId
  bookForm = this.fb.nonNullable.group({
    title: ['', [Validators.required]],
    isbn: ['', [Validators.required]],
    authorId: this.fb.control<number | null>(null, [Validators.required, Validators.min(1)]),
    price: [0, [Validators.required, Validators.min(0)]],
    genre: ['', [Validators.required]],
    published: this.fb.control<Date | null>(null, [Validators.required]),
  });
 
  initForm(data?: Book) {
    // 预加载作者选项(活信号)
    this.dispatch.loadAuthors({ page: 0, size: 100 });
 
    // 读写不对称性适配:读数据包含嵌套 author 对象,回填时解构取 author.id
    if (data) {
      this.bookForm.patchValue({
        title: data.title,
        isbn: data.isbn,
        authorId: data.author.id ?? null,
        price: data.price,
        genre: data.genre,
        published: data.published ? new Date(data.published) : null,
      });
    }
  }
 
  toPayload(): BookRequest {
    const raw = this.bookForm.getRawValue();
    return {
      title: raw.title,
      isbn: raw.isbn,
      authorId: raw.authorId!,
      price: raw.price,
      genre: raw.genre,
      published: raw.published ? raw.published.toISOString().split('T')[0] : '',
    };
  }
}

4. CRUD 状态跃迁与变更新鲜度管线拓扑

流程架构图
Mermaid

5. CRUD 治理避坑清单 (Do's & Don'ts)

错误实践 (Don't)正确实践 (Do)
在写操作成功后,手动将新对象 append 到本地数组。触发声明式重新加载管线(reloadAfterMutation$),让数据库统一仲裁排序与总数。
在搜索输入和快速分页时使用 mergeMap 或 concatMap。使用 switchMap 处理读查询,自动废弃过时的在途请求,防止网络乱序污染视图。
在提交和删除操作中使用普通处理函数,导致按钮多次连击产生重复写入。使用 exhaustMap 拦截重复事件,在上一次异步网络请求终结前抑制新的动作。
前端创建实体时将整个嵌套的关联对象整体向后端提交。实行读写不对称性契约:查询读取展示对象,创建更新仅传递标量外键 authorId。
跨组件级联选择时每个弹窗内部独立发起全量数据请求。直接复用全局 AuthorStore 的活信号状态,实现跨弹窗跨组件的低开销实时感知。