使用 @ngrx/signals 时,如何编写一个可重用的 CRUD 插件?

解读

在国内一线/二线大厂的 Angular 面试中,“可重用”与“插件化”是高频关键词。面试官并非只想听到“我会写 CRUD”,而是想确认你能否把状态逻辑封装成无侵入、可组合、可插拔的 Signal Store 插件,并兼顾类型安全、可测试性与性能。
因此,回答必须体现三点:

  1. 插件必须基于 @ngrx/signals 的 withCalls / withMethods / withState 组合,而非直接改原型。
  2. 对 Entity 的增删改查要抽象成泛型接口,让业务层只传实体类型与主键字段名即可。
  3. 必须展示国内真实场景的坑点:如分页缓存、乐观更新、批量删除、权限拦截、中文提示等。

知识点

  • @ngrx/signals 插件本质:一个高阶函数 withCrud<T, K extends keyof T>,返回 SignalStoreFeature。
  • Entity 主键支持自定义字段(默认 'id'),兼容 MongoDB 的 _id。
  • 乐观更新需用 patchState + rollbackOnError,与后端返回对齐字段,防止出现“闪现”问题。
  • 分页插件与 CRUD 插件正交,通过 withPagination 组合,避免“大杂烩”store。
  • 中文错误提示需封装成 inject(CrudMessageService),方便统一替换为 Ant Design 的 nz-message。
  • 单元测试必须覆盖:
    – 乐观更新后失败回滚;
    – 主键冲突;
    – 空数组删除无异常;
    – 类型推导不丢失。

答案

下面给出可直接落地的可重用 CRUD 插件源码(精简但完整,面试时可手写骨架,口述细节)。

// crud-plugin.ts
import { inject } from '@angular/core';
import { patchState, signalStoreFeature, withMethods, withState, SignalStoreFeature } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe, switchMap, tap, catchError, of, EMPTY } from 'rxjs';

export interface CrudState<T> {
  entities: T[];
  loaded: boolean;
  error: string | null;
}

export type CrudMethods<T, K extends keyof T> = {
  loadAll: () => void;
  add: (entity: Omit<T, K>) => void;
  update: (id: T[K], changes: Partial<Omit<T, K>>) => void;
  remove: (id: T[K]) => void;
};

export function withCrud<T extends { [key: string]: any }, K extends keyof T = 'id'>(
  options: {
    key?: K;
    loadAllApi: () => Observable<T[]>;
    addApi: (entity: Omit<T, K>) => Observable<T>;
    updateApi: (id: T[K], changes: Partial<Omit<T, K>>) => Observable<T>;
    removeApi: (id: T[K]) => Observable<void>;
    onError?: (msg: string) => void; // 默认 inject(CrudMessageService).error
  }
): SignalStoreFeature<
  { state: CrudState<T> },
  { state: CrudState<T>; methods: CrudMethods<T, K> }
> {
  const key = (options.key ?? 'id') as K;
  return signalStoreFeature(
    withState<CrudState<T>>({ entities: [], loaded: false, error: null }),
    withMethods((store) => {
      const onError = options.onError ?? inject(CrudMessageService).error;

      return {
        loadAll: rxMethod<void>(
          pipe(
            tap(() => patchState(store, { loaded: false, error: null })),
            switchMap(() =>
              options.loadAllApi().pipe(
                tap((entities) => patchState(store, { entities, loaded: true })),
                catchError((e) => {
                  const msg = '加载失败:' + (e?.message ?? '网络异常');
                  onError(msg);
                  patchState(store, { error: msg });
                  return EMPTY;
                })
              )
            )
          )
        ),

        add: rxMethod<Omit<T, K>>(
          pipe(
            switchMap((payload) => {
              const temp: T = { ...payload, [key]: '__tmp_' + Date.now() } as T;
              patchState(store, { entities: [...store.entities(), temp] });
              return options.addApi(payload).pipe(
                tap((entity) => {
                  const list = store.entities().map((i) =>
                    (i[key] as any) === temp[key] ? entity : i
                  );
                  patchState(store, { entities: list });
                }),
                catchError((e) => {
                  const list = store.entities().filter((i) => (i[key] as any) !== temp[key]);
                  patchState(store, { entities: list });
                  onError('新增失败:' + (e?.message ?? '服务器异常'));
                  return EMPTY;
                })
              );
            })
          )
        ),

        update: rxMethod<{ id: T[K]; changes: Partial<Omit<T, K>> }>(
          pipe(
            switchMap(({ id, changes }) => {
              const origin = store.entities().find((i) => i[key] === id);
              if (!origin) return EMPTY;
              patchState(store, {
                entities: store.entities().map((i) =>
                  i[key] === id ? { ...i, ...changes } : i
                ),
              });
              return options.updateApi(id, changes).pipe(
                catchError((e) => {
                  patchState(store, {
                    entities: store.entities().map((i) =>
                      i[key] === id ? origin : i
                    ),
                  });
                  onError('更新失败:' + (e?.message ?? '服务器异常'));
                  return EMPTY;
                })
              );
            })
          )
        ),

        remove: rxMethod<T[K]>(
          pipe(
            switchMap((id) => {
              const origin = store.entities().filter((i) => i[key] !== id);
              patchState(store, { entities: origin });
              return options.removeApi(id).pipe(
                catchError((e) => {
                  patchState(store, { entities: [...store.entities(), ...store.entities()] }); // 回滚
                  onError('删除失败:' + (e?.message ?? '服务器异常'));
                  return EMPTY;
                })
              );
            })
          )
        ),
      };
    })
  );
}

使用示例(面试现场手写):

export const ProductStore = signalStore(
  withState({ filter: '' }),
  withCrud<Product, 'id'>({
    key: 'id',
    loadAllApi: () => inject(ProductService).getAll(),
    addApi: (dto) => inject(ProductService).add(dto),
    updateApi: (id, dto) => inject(ProductService).update(id, dto),
    removeApi: (id) => inject(ProductService).delete(id),
  })
);

拓展思考

  1. 权限插件组合:再写一个 withAcl(['product:add']),在 add 方法前拦截,无权限直接 onError('暂无新增权限'),实现插件链式组合。
  2. 分页与 CRUD 解耦:withPagination 只关心 pageIndex / pageSize / total,CRUD 插件不依赖分页字段,通过 loadAllApi 内部自己传参,保持正交性。
  3. WebSocket 增量同步:在插件内部再开一个 wsSubscription,收到 wsAdd 时直接 patchState 插入,避免重新拉全量,面试时提到这点可加分。
  4. 国内低码平台实践:把插件打包成 npm 私库,通过 forRoot 提供全局配置(如统一错误码映射),让多条业务线零成本接入,体现工程化思维。