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

如何将NgRx Toolkit+SignalStore代码拆分到对应文件?

拆分NgRx Toolkit + SignalStore代码到独立文件

1. reducer.ts

import { flightActions } from './actions';
import { updateState, OnFn } from '@angular-architects/ngrx-toolkit';
import { Flight } from './flight';

export const flightReducer = (actions: typeof flightActions, on: OnFn) => {
  on(actions.private.loaded, (state, { flights }) => {
    updateState(state, 'flights loaded', { flights });
  });
};

2. effects.ts

import { flightActions } from './actions';
import { inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map, switchMap } from 'rxjs';
import { Flight } from './flight';
import { CreateEffectFn } from '@angular-architects/ngrx-toolkit';

export const flightEffects = (actions: typeof flightActions, create: CreateEffectFn) => {
  const httpClient = inject(HttpClient);

  return {
    loadFlights$: create(actions.public.load).pipe(
      switchMap(({ from, to }) => {
        return httpClient.get<Flight[]>(
          'https://demo.angulararchitects.io/api/flight',
          {
            params: new HttpParams().set('from', from).set('to', to),
          }
        );
      }),
      map((flights) => actions.private.loaded({ flights }))
    ),
  };
};

3. 主文件 flight.store.ts

import { signalStore, withState } from '@ngrx/signals';
import { withDevtools, withRedux } from '@angular-architects/ngrx-toolkit';
import { Flight } from './flight';
import { flightActions } from './actions';
import { flightReducer } from './reducer';
import { flightEffects } from './effects';

export const FlightStore = signalStore(
  { providedIn: 'root' },
  withDevtools('flights'),
  withState({ flights: [] as Flight[] }),
  withRedux({
    actions: flightActions,
    reducer: flightReducer,
    effects: flightEffects,
  })
);

相关库问题说明(翻译自原讨论内容)

该讨论围绕withRedux配置的代码拆分展开,社区确认了可行方案:

  • 将reducer封装为接收actions和on参数的独立函数导出
  • 将effects封装为接收actions和create参数的独立函数导出
  • 在withRedux配置中直接引用上述导出函数,即可实现符合传统NgRx模式的文件拆分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 23:18:21