You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NGXS调度数据获取动作前是否会自动检查store避免调用API?

关于NGXS数据复用能力的问题解答
  • NGXS本身没有内置调度动作前自动检查Store中已有数据、拦截重复API请求的默认特性,框架本身只负责动作的分发和状态流转,具体的动作处理逻辑完全由开发者定义的Action handler控制。
  • 你不需要每次在组件侧调度数据获取类动作时都手动做存在性校验,更合理的实现是将校验逻辑封装在对应Action的处理函数内部,一次封装全局生效,组件侧无需修改原有调用逻辑。

基础实现示例

在State类的Action处理函数中添加数据存在性判断即可:

import { State, Action, StateContext } from '@ngxs/store';
import { FooActions } from './foo.actions';
import { FooService } from './foo.service';

export interface FooStateModel {
  fooList: any[];
}

@State<FooStateModel>({
  name: 'foo',
  defaults: {
    fooList: []
  }
})
export class FooState {
  constructor(private fooService: FooService) {}

  @Action(FooActions.GetAll)
  getAllFoo(ctx: StateContext<FooStateModel>) {
    const currentState = ctx.getState();
    // 本地已有数据时直接返回,不发起API请求
    if (currentState.fooList.length > 0) {
      return;
    }
    // 无数据时发起请求更新状态
    return this.fooService.getAllFoo().pipe(
      tap(res => ctx.patchState({ fooList: res }))
    );
  }
}

支持强制刷新的扩展实现

如果存在需要主动拉取最新数据的场景,可以给Action增加可选的强制刷新参数:

  1. 修改Action定义:
export class GetAll {
  static readonly type = '[Foo] Get All';
  constructor(public forceRefresh?: boolean) {}
}
  1. 适配Action处理函数:
@Action(FooActions.GetAll)
getAllFoo(ctx: StateContext<FooStateModel>, action: FooActions.GetAll) {
  const currentState = ctx.getState();
  // 非强制刷新且已有数据时直接返回
  if (!action.forceRefresh && currentState.fooList.length > 0) {
    return;
  }
  return this.fooService.getAllFoo().pipe(
    tap(res => ctx.patchState({ fooList: res }))
  );
}
  1. 按需调用:
// 普通调用,优先复用本地数据
this.store.dispatch(new FooActions.GetAll());
// 强制刷新调用,跳过本地校验直接发起请求
this.store.dispatch(new FooActions.GetAll(true));

内容的提问来源于stack exchange,提问作者Jed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:06:05