如何将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
相关产品推荐
相关产品推荐

