首页 > 解决方案 > 我如何将 NgRx 中的所有减速器导出到一个索引文件中?

问题描述

嘿,我在 Reducer 文件夹中有 2 个减速器,

commentReducer:
import { Comment } from '../models/comment.model';
import * as CommentAction from '../actions/comment.actions';
import { Action, createReducer, on } from '@ngrx/store';

export const initialState: Comment[] = [];

const commentReducer = createReducer(
  initialState,
  on(CommentAction.addcomment, (state, { fullName, comment }) => [...state, { fullName, comment }]),
  on(CommentAction.removecomment, (state, { index }) => {
    const array = [...state];
    array.splice(index, 1);
    return array;
 })
);

export function reducer(state: Comment[], action: Action) {
  return commentReducer(state, action);
}

用户减速器:

import { User } from '../models/user.model';
import * as UserAction from '../actions/user.actions';
import { Action, createReducer, on } from '@ngrx/store';

export const initialState: User = {
  userId: null,
  id: null,
  title: null,
  completed: null
};

const userReducer = createReducer(
  initialState,
  on(UserAction.loaduser, (state, payload) => payload)
);

export function reducer(state: User, action: Action) {
  return userReducer(state, action);
}

我像这样将reducer导入到应用程序模块中:app.module:

import * as commentReducer from './reducers/comment.reducer';
import * as userReducer from './reducers/user.reducer';

    StoreModule.forRoot({
      comment: commentReducer.reducer,
      user: userReducer.reducer
    }),

但是我的应用程序增长了,我添加了更多的减速器。如何在我的减速器文件夹中创建一个索引文件并将所有减速器一起导出并使其在 app.module 中看起来像这样:

   StoreModule.forRoot(AllReducer),

类似的东西...谢谢

标签: angularngrx

解决方案


您可以将每个 reducer 及其操作、模型或效果放在 reducers 文件夹中的一个特殊文件夹中,然后在 app.module.ts 中像这样导入它们:

import { reducers } from './reducers';

在进口部分:

StoreModule.forRoot(reducers)

演示和结构


推荐阅读