本文介绍了在@ ngrx/store 4.0中提供root减速器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在@ ngrx/store 2.0中,我们可以将root reducer作为函数提供,然后从那里在应用程序内部拆分逻辑.在更新到@ ngrx/store 4.0之后,我无法再使用此功能,因为我看到的是reducers必须是reducers的映射,它将在状态下的相同键下创建对象.有没有办法在@ ngrx/store 4.0中使用旧的行为?在我的状态组件中,我知道彼此之间的状态,因此我需要能够动态拆分状态,还需要能够将动作分派给我的正确的reducer自己的方式.另外,应用程序还会分成多个延迟加载的路由,在某些情况下,这些路由会重用其他功能的数据.

In @ngrx/store 2.0 we could provide the root reducer as a function and from there we split our logic inside the application. After I updated to @ngrx/store 4.0 I cannot use this feature any more from what I can see the reducers need to be a map of reducers which will create objects under the same keys in the state. Is there a way to use the old behavoir in @ngrx/store 4.0 In my state components are aware one of another and I need to be able to split my state dynamically also I need to be able to dispatch actions to the right reducer in my own way. Also app is splitted in multiple lazy loaded routes which in some cases reuse the data from another feature.

 StoreModule.provideStore(reducer, {
      auth: {
        loggedIn: true
      }
    })

StoreModule.forRoot(reducers, {
      initialState: {
        auth: {
          loggedIn: true
        }
      }
    })

我需要reducers是一个获取完整状态并将其分派给正确的reducer的函数,有没有办法实现这种行为?

I need reducers to be a function which gets the full state and dispatches it to the correct reducer, Is there a way to achieve this behavior?

推荐答案

在对ngrx存储库进行了第二次查看之后,我发现了它.为了获得想要的结果,我们需要用新的实现替换@ ngrx/store reducer工厂.我注入了一个新的减速器工厂,现在该应用程序可以像以前一样工作.有关如何在工厂中更换减速器的简单代码示例.

After I had a second look over ngrx repo I figured it out. To achieve the wanted result we need to replace the @ngrx/store reducer factory with a new implementation. I injected a new reducer factory and right now the application works as before. Simple code sample on how to replace the reducer factory it.

// This factory replaces @ngrx combine reducers so we can manage how we split the keys inside the state
export function combineReducersFactory(
    reducers: any,
    initialState: any = {}
): ActionReducer<any, Action> {
    return function combination(state = initialState, action) {
        const nextState: any = reducers(state, action);
        return nextState !== state ? nextState : state;
    };
}

export const NG_RX_STORE_PROVIDER = [
    StoreModule.forRoot(rootReducer, createEmptyState()),
];

export const NG_RX_REDUCER_FACTORY = [
    {
        provide: REDUCER_FACTORY,
        useFactory: () => combineReducersFactory
    }
];

@NgModule({
    imports: [
        ...NG_RX_STORE_PROVIDER
    ],
    declarations: [...APP_COMPONENTS, ...AG_GRID_COMPONENTS],
    providers: [...NG_RX_REDUCER_FACTORY]
})
export class AppModule {
}

这篇关于在@ ngrx/store 4.0中提供root减速器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:03